我正在使用Node.js编写应用程序。
我想创建的一个功能是打开默认的Web浏览器并导航到特定的URL。
我希望它是可移植的,可以在Windows/Mac/Linux上运行。
我正在使用Node.js编写应用程序。
我想创建的一个功能是打开默认的Web浏览器并导航到特定的URL。
我希望它是可移植的,可以在Windows/Mac/Linux上运行。
使用 open(以前称为 opn
)因为它可以解决跨平台问题。安装方式如下:
$ npm install open
使用方法:
const open = require('open');
// opens the url in the default browser
open('http://sindresorhus.com');
// specify the app to open in
open('http://sindresorhus.com', {app: 'firefox'});
var url = 'http://localhost';
var start = (process.platform == 'darwin'? 'open': process.platform == 'win32'? 'start': 'xdg-open');
require('child_process').exec(start + ' ' + url);
&
符号需要用^&
进行转义。 - junvar安装:
$ npm install open
使用方法:
const open = require('open');
(async () => {
// Opens the image in the default image viewer and waits for the opened app to quit.
await open('unicorn.png', {wait: true});
console.log('The image viewer app quit');
// Opens the URL in the default browser.
await open('https://sindresorhus.com');
// Opens the URL in a specified browser.
await open('https://sindresorhus.com', {app: 'firefox'});
// Specify app arguments.
await open('https://sindresorhus.com', {app: ['google chrome', '--incognito']});
})();
Windows + Express
app.listen(3000, ()=>{
require('child_process').exec('start http://localhost:3000/');
});
require('os').type()
然后根据平台使用 spawn("open")
或者 spawn("xdg-open")
来执行操作?
require('child_process').spawn('explorer', ['url'])
这个一行命令真不错! - TWiStErRob简单使用
require('child_process').exec('start https://www.google.co.in/');
这对我有用。
在我看来,最简单和最整洁的方法是使用一个名为openurl的npm包。执行npm install openurl
即可。你可以在Nodejs REPL中快速尝试一下。
require("openurl").open("https://dev59.com/t2oy5IYBdhLWcg3wguWS")
如果需要,你也可以使用它发送电子邮件,像这样;require("openurl").open("mailto:janedoe@example.com")
#!/usr/bin/env node
const url = 'http://localhost'
require('child_process')
.exec((process.platform
.replace('darwin','')
.replace(/win32|linux/,'xdg-') + 'open ' + url));
var url = '\\index.html';
var start = (process.platform == 'darwin'? 'open': process.platform == 'win32'? 'start': 'xdg-open');
require('child_process').exec(start + ' ' + __dirname + url);
Lexa-B 的回答对我最有效,但是我遇到了“Windows 无法找到 index.html”错误。我正在使用 Lexa-B 的代码 child_process exec 命令来打开我正在编写的 npm 包中的本地网页。当我使用 npx 命令在 package bin.js 中运行它/打开它时,需要打开一个 html 文件。
需要做的只是将 __dirname 追加到文件路径中,以确保相对目录路径正确,用于调用 child_process 的文件。child_process 运行在主文件夹中,远离 npx 临时文件位置。__dirname 解决了这个问题并连接了两者,解决了我的文件缺失错误。