Categories
JavaScript Answers

How to launch a browser from the a Node.js command line script?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *