1.打開瀏覽器
最簡單的方法:
const cp = require('child_process')
cp.exec('start http://127.0.0.1:8889/'); // 自動打開默認瀏覽器
另一種方法是安裝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']});
})();
可以看到支持的功能更全面,對各平台的支持也有保證。
2.打開指定的應用程序
這里打開VS CODE
const exec = require('child_process').execFile;
const path = "D:\\Program Files\\Microsoft VS Code\\Code.exe"
exec(path, function(err, data) { if (err) { throw err; } console.log(data.toString()); });
將會打開VS CODE
在windows下怎么獲取程序的運行參數呢?
可以先右鍵用vs code打開一個項目
然后win + r 打開 運行程序

輸入wmic 回車
查看所有運行中進程的命令行參數:
wmic process get caption,commandline /value
查詢指定進程的命令行參數:
wmic process where caption="notepad.exe" get caption,commandline /value【精確查找】
wmic process where="caption like 'notepad%'" get caption,commandline /value【模糊查找】
所以,打開指定的目錄就可以通過如下代碼實現了:
const exec = require('child_process').execFile;
const path = "D:\\Program Files\\Microsoft VS Code\\Code.exe"
exec(path, ['目錄路徑'], function(err, data) {
if (err) {
throw err;
}
console.log(data.toString());
});
nice!
喜歡這篇文章?歡迎打賞~~

