Node.js 子進(jìn)程運(yùn)行CMD命令詳解
本文將介紹如何在 Node.js 中通過 child_process 模塊使用 exec、execFile 和 spawn 三種方法來創(chuàng)建子進(jìn)程運(yùn)行cmd運(yùn)行,并通過示例說明了每種方法的參數(shù)和輸出處理方式。
在介紹子進(jìn)程前先創(chuàng)建一個(gè)node腳本名為printArgs.js,該腳本的作用是接收參數(shù)并將參數(shù)輸出。后續(xù)將使用node子進(jìn)程調(diào)用該腳本。腳本代碼如下:
// 獲取命令行參數(shù),process.argv 是一個(gè)數(shù)組,其中包含了命令行參數(shù)
// 第一個(gè)元素是 node 的路徑,第二個(gè)元素是腳本文件的路徑,從第三個(gè)元素開始是用戶傳入的參數(shù)
const args = process.argv.slice(2);
// 打印傳入的參數(shù)
console.log("傳入的參數(shù)為:");
args.forEach((arg, index) => {
setTimeout(() => {
console.log(`${index + 1}: ${arg}`);
}, (index + 1) * 1000);
});
該腳本通過 process.argv 獲取命令行參數(shù),并延遲打印每個(gè)參數(shù),模擬異步處理流程。
- process.argv:Node.js 中獲取命令行參數(shù)的數(shù)組:
- argv[0]: Node 可執(zhí)行文件路徑
- argv[1]: 當(dāng)前執(zhí)行的腳本路徑
- argv[2...]: 用戶輸入的參數(shù)
- setTimeout:每個(gè)參數(shù)延遲 (index + 1) * 1000 毫秒后打印
創(chuàng)建index.js腳本,引入了 Node.js 的 child_process 模塊中的三個(gè)方法,下面將分別介紹這三個(gè)方法的區(qū)別
const { exec, execFile, spawn } = require("child_process");
1.exec
let execChild = exec(
"node ./printArgs.js aaa bbb ccc",
{ encoding: "utf8" },
(error, stdout, stderr) => {
if (error) {
console.log(`執(zhí)行錯(cuò)誤:${error}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
}
console.log(`stdout: ${stdout}`);
}
);
execChild.on("close", (code) => {
console.log(`子進(jìn)程退出,退出碼$[code]`);
})方法說明: exec(command[, options][, callback])
適用場(chǎng)景:執(zhí)行一條 shell 命令并一次性獲取輸出(適合小輸出量任務(wù)),即運(yùn)行printArgs腳本后將等待3秒一次性輸出 aaa bbb ccc
參數(shù):
- command:完整的 shell 命令字符串。
- encoding: 設(shè)置輸出編碼,如 "utf8"。
- callback:回調(diào)函數(shù),獲取 error、stdout(標(biāo)準(zhǔn)輸出)、stderr(錯(cuò)誤輸出)。
- execChild.on("close", callback):監(jiān)聽子進(jìn)程關(guān)閉事件,獲取退出碼。
2.execFile
let fileChild = execFile(
"node",
["printArgs.js", "aaa", "bbb", "ccc"],
{ encoding: "utf8", cwd: "" }, //cwd為工作目錄
(error, stdout, stderr) => {
if (error) {
console.error(`執(zhí)行出錯(cuò): ${error}`);
return;
}
if (stderr) {
console.error(`stderr: ${stderr}`);
}
console.log(`stdout: ${stdout}`);
}
);
fileChild.on("close", (code) => {
console.log(`子進(jìn)程退出,退出碼$[code]`);
});方法說明 execFile(file[, args][, options][, callback])
適用場(chǎng)景:直接運(yùn)行某個(gè)可執(zhí)行文件,代碼中使用node執(zhí)行printArgs腳本,等待3秒后一次性輸出 aaa bbb ccc
參數(shù):
- file: 可執(zhí)行文件或腳本(如 node)。
- args: 參數(shù)數(shù)組,即["printArgs.js", "aaa", "bbb", "ccc"]
- cwd: 工作目錄(空字符串為當(dāng)前目錄)。
- encoding: 輸出編碼。
- callback: 同上,獲取輸出結(jié)果。
- fileChild.on("close", callback):監(jiān)聽子進(jìn)程關(guān)閉事件,獲取退出碼。
3.spawn
const spawnChild = spawn("node", ["./printArgs.js", "aaa", "bbb", "ccc"], {
shell: true,
}); // 在 Windows 上執(zhí)行 CMD 命令時(shí),通常需要設(shè)置 { shell: true }
spawnChild.stdout.on("data", (data) => {
console.log(`stdout: ${data}`);
});
spawnChild.stderr.on("data", (data) => {
console.error(`stderr: ${data}`);
});
spawnChild.on("close", (code) => {
console.log(`子進(jìn)程退出,退出碼 $[code]`);
})方法說明 spawn(command[, args][, options])
適用場(chǎng)景:持續(xù)處理大數(shù)據(jù)流、監(jiān)聽標(biāo)準(zhǔn)輸出/錯(cuò)誤(如服務(wù)器日志),代碼中調(diào)用printArgs腳本將每隔1秒輸出內(nèi)容
參數(shù):
- command: 執(zhí)行命令。
- args: 參數(shù)數(shù)組,即["./printArgs.js", "aaa", "bbb", "ccc"]
- shell: true:在 Windows 下推薦啟用,執(zhí)行 shell 命令時(shí)必要。
- spawnChild.on實(shí)時(shí)監(jiān)聽標(biāo)準(zhǔn)輸出/錯(cuò)誤。
總結(jié)對(duì)比
| 方法 | 是否用 shell | 適用場(chǎng)景 | 是否支持大數(shù)據(jù)流 | 回調(diào)/事件模型 |
|---|---|---|---|---|
| exec | 是 | 簡(jiǎn)單命令 + 小輸出 | 否 | 回調(diào)函數(shù) |
| execFile | 否 | 執(zhí)行文件 + 安全性要求高 | 否 | 回調(diào)函數(shù) |
| spawn | 否(可選) | 大數(shù)據(jù)流 / 持續(xù)輸出任務(wù) | 是 | 事件監(jiān)聽 |
到此這篇關(guān)于Node.js 子進(jìn)程運(yùn)行CMD命令詳解的文章就介紹到這了,更多相關(guān)Node.js 子進(jìn)程運(yùn)行CMD內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Node.js實(shí)現(xiàn)解析post請(qǐng)求的方法詳解
這篇文章主要為大家詳細(xì)介紹了Node.js實(shí)現(xiàn)解析post請(qǐng)求方法的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,有需要的小伙伴可以了解下2024-04-04
nodejs基礎(chǔ)之多進(jìn)程實(shí)例詳解
這篇文章主要介紹了nodejs基礎(chǔ)之多進(jìn)程,結(jié)合實(shí)例形式分析了nodejs多進(jìn)程的概念、原理、相關(guān)函數(shù)使用方法及操作注意事項(xiàng),需要的朋友可以參考下2018-12-12
淺談node如何優(yōu)雅地獲取mac系統(tǒng)版本
這篇文章主要和大家聊聊node如何優(yōu)雅地獲取mac系統(tǒng)版本,文中有詳細(xì)的代碼示例和流程步驟,對(duì)我們學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-06-06
nodejs+socket.io實(shí)現(xiàn)p2p消息實(shí)時(shí)發(fā)送的項(xiàng)目實(shí)踐
本文主要介紹了nodejs+socket.io實(shí)現(xiàn)p2p消息實(shí)時(shí)發(fā)送,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
node thread.sleep實(shí)現(xiàn)示例
這篇文章主要介紹了node thread.sleep實(shí)現(xiàn)示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-06-06

