How to use nodejs to open default browser and navigate to a specific URL

How to use nodejs to open default browser and navigate to a specific URL

I’m writing an application using Node.js.
One of the functions I want to create is to open the default web browser and navigate to a specific URL.
I want it to be portable so that it runs on Windows/Mac/Linux.

Solutions/Answers:

Solution 1:

Use opn because it will handle the cross platform issue. To install:

$ npm install opn

To use:

var opn = require('opn');

// opens the url in the default browser 
opn('http://sindresorhus.com');

// specify the app to open in 
opn('http://sindresorhus.com', {app: 'firefox'});

Solution 2:

var url = 'http://localhost';
var start = (process.platform == 'darwin'? 'open': process.platform == 'win32'? 'start': 'xdg-open');
require('child_process').exec(start + ' ' + url);

Solution 3:

node-open is deprecated. Now use opn:

const opn = require('opn')

opn('http://sindresorhus.com') // Opens the url in the default browser

//opn('http://sindresorhus.com', {app: 'firefox'}) // Specify the app to open in

Solution 4:

you may need to implement a switch using the value of …

require('os').type()

and the use spawn(“open”) or spawn(“xdg-open”) depending on the platform?

Solution 5:

The easiest and neatest way, IMHO is using an npm package called openurl. Do a npm install openurl . You could try this real quick in your Nodejs REPL

require("openurl").open("http://stackoverflow.com/questions/8500326/how-to-use-nodejs-to-open-default-browser-and-navigate-to-a-specific-url")

You could also send emails with it if the need arises like so;
require("openurl").open("mailto:janedoe@example.com")