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?
To use Node. js to open default browser and navigate to a specific URL, we can use the open package. const open = require("open"); open("http://example.com"); open("http://example.com", { app: "firefox" }); to call open to open the URL we pass into it.
The usual way to run a Node. js program is to run the globally available node command (once you install Node. js) and pass the name of the file you want to execute. While running the command, make sure you are in the same directory which contains the app.
Open exists now, use that. :)
Install with:
$ npm install --save open
Use with:
const open = require('open'); // Opens the image in the default image viewer (async () => { await open('unicorn.png', {wait: true}); console.log('The image viewer app closed'); // Opens the url in the default browser await open('https://sindresorhus.com'); // Specify the app to open in await open('https://sindresorhus.com', {app: 'firefox'}); // Specify app arguments await open('https://sindresorhus.com', {app: ['google chrome', '--incognito']}); })();
app: ...
option:Type: string | string[]
Specify the app to open the target with, or an array with the app and app arguments.
The app name is platform dependent. Don't hard code it in reusable modules. For example, Chrome is google chrome on macOS, google-chrome on Linux and chrome on Windows.
You may also pass in the app's full path. For example on WSL, this can be /mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe for the Windows installation of Chrome.
Example:
open('http://localhost', {app: "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With