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.

3

8 Answers

Use open (formerly known as opn) because it will handle the cross platform issue. To install:

$ npm install open 

To use:

const open = require('open'); // opens the url in the default browser open('); // specify the app to open in open(' {app: 'firefox'}); 
10
var url = ' var start = (process.platform == 'darwin'? 'open': process.platform == 'win32'? 'start': 'xdg-open'); require('child_process').exec(start + ' ' + url); 
2

node-open is deprecated. Now use open:

const open = require('open') await open(') // Opens the url in the default browser await open(' {app: 'firefox'}) // Specify the app to open in 
0

You may need to implement a switch using the value of ...

require('os').type() 

And then use spawn("open") or spawn("xdg-open") depending on the platform?

2

Install:

$ npm install open 

Usage:

const open = require('open'); (async () => { // Opens the image in the default image viewer and waits for the opened app to quit. await open('unicorn.png', {wait: true}); console.log('The image viewer app quit'); // Opens the URL in the default browser. await open('); // Opens the URL in a specified browser. await open(' {app: 'firefox'}); // Specify app arguments. await open(' {app: ['google chrome', '--incognito']}); })(); 
1

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("")

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

Windows + Express

app.listen(3000, ()=>{ require('child_process').exec('start ); }); 
#!/usr/bin/env node const url = ' require('child_process') .exec((process.platform .replace('darwin','') .replace(/win32|linux/,'xdg-') + 'open ' + url)); 
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy