How would you launch a browser from the a node.js

2019-02-11 09:52发布

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

I don't know if it matters, but I am on OSX.

I know you can launch a browser from the command line itself by typing:

open http://www.stackoverflow.com

But is there a way to open a browser from inside a nodejs command line script?

1条回答
▲ chillily
2楼-- · 2019-02-11 10:48

Opn exists now, use that. :)

Install with:

$ npm install --save opn

Use with:

const opn = require('opn');

// Opens the image in the default image viewer
opn('unicorn.png').then(() => {
    // image viewer closed
});

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

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

// Specify app arguments
opn('http://sindresorhus.com', {app: ['google chrome', '--incognito']});var open = require('open');

    open('http://www.google.com');

You can also select a specific browser:

    open('http://www.google.com', 'firefox');

Or handle an error callback:

    open('http://www.google.com', function (err) {
      if (err) throw err;
      console.log('The user closed the browser');
    });
查看更多
登录 后发表回答