如何从Node.js命令行脚本启动浏览器

58

我不知道这是否重要,但我正在使用OSX系统。

我知道你可以通过在命令行中键入以下内容来启动浏览器:

open http://www.stackoverflow.com

但是有没有一种方法可以从nodejs命令行脚本内部打开浏览器呢?

1个回答

123

Open 现在已存在,请使用它。 :)

安装方法:

$ npm install --save open

适用于:

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: ...选项:

类型:字符串 | 字符串数组

指定打开目标时要使用的应用程序,或者是一个包含应用程序和应用程序参数的数组。

应用程序名称因平台而异。不要将其硬编码到可重用模块中。例如,在 macOS 上,Chrome 是google chrome,在 Linux 上是google-chrome,在 Windows 上是chrome。

您还可以传递应用程序的完整路径。例如,在 WSL 上,这可能是Chrome的Windows安装的/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe。

示例:

open('http://localhost', {app: "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"});


5
Linux和Windows怎么样? - chovy
2
我相信xdg-open是Linux上open命令的标准版本,但是我不知道Windows上应该使用什么。 - ctide
10
https://github.com/fixedset/open.js 处理跨平台问题。 - Paul Irish
4
"opn"(不是打错字,它不含有 "e")似乎是最近很流行使用的新工具。https://www.npmjs.com/package/opn - chamberlainpi
6
Node Open已被弃用,请更新至https://github.com/sindresorhus/opn。 - Chris Calo
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接