Sometimes, we want to launch a browser from the a Node.js command line script.
In this article, we’ll look at how to launch a browser from the a Node.js command line script.
How to launch a browser from the a Node.js command line script?
To launch a browser from the a Node.js command line script, we can use the open
package.
To install it, we run
npm install --save open
Then we use it by writing
const open = require("open");
(async () => {
await open("unicorn.png", { wait: true });
await open("https://example.com");
await open("https://example.com", { app: "firefox" });
await open("https://example.com", {
app: ["google chrome", "--incognito"],
});
})();
to call open
with a file path with
await open("unicorn.png", { wait: true });
We set wait
to true
to wait for the file to open.
Also, we can call it with a URL with
await open("https://sindresorhus.com");
to open the browser with the URL.
We specify the app
option to set the program to open.
Also, we can pass in command line arguments for the app being opened with
await open("https://sindresorhus.com", {
app: ["google chrome", "--incognito"],
});
Conclusion
To launch a browser from the a Node.js command line script, we can use the open
package.