您将如何从 node.js 命令行脚本启动浏览器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7664605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:39:12  来源:igfitidea点击:

How would you launch a browser from the a node.js command line script

shellcommand-linenode.js

提问by Bob Ralian

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

可能的重复:
如何使用 nodejs 打开默认浏览器并导航到特定 URL

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

我不知道这是否重要,但我在 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?

但是有没有办法从 nodejs 命令行脚本内部打开浏览器?

回答by ctide

Openexists now, use that. :)

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

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']});
})();

The app: ...option:

app: ...选项:

Type: string | string[]

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.

指定用于打开目标的应用程序,或带有 app 和 app 参数的数组。

应用程序名称取决于平台。不要在可重用模块中对其进行硬编码。例如,Chrome 在 macOS 上是 google chrome,在 Linux 上是 google-chrome,在 Windows 上是 chrome。

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

Example:

例子:

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

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