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])
適用場景:執(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])
適用場景:直接運(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])
適用場景:持續(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é)對比
| 方法 | 是否用 shell | 適用場景 | 是否支持大數(shù)據(jù)流 | 回調(diào)/事件模型 |
|---|---|---|---|---|
| exec | 是 | 簡單命令 + 小輸出 | 否 | 回調(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一會(huì)帶你學(xué)會(huì)用Webpack搭建開發(fā)環(huán)境并打包代碼
這篇文章主要給大家介紹了關(guān)于如何用Webpack搭建開發(fā)環(huán)境并打包的相關(guān)資料,webpack是一個(gè)現(xiàn)代JavaScript應(yīng)用程序的靜態(tài)模塊打包器(module bundler),需要的朋友可以參考下2023-08-08
基于nodejs的微信JS-SDK簡單應(yīng)用實(shí)現(xiàn)
這篇文章主要介紹了基于nodejs的微信JS-SDK簡單應(yīng)用實(shí)現(xiàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-05-05
Node.js npm命令運(yùn)行node.js腳本的方法
今天小編就為大家分享一篇Node.js npm命令運(yùn)行node.js腳本的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10
Windows 系統(tǒng)下安裝和部署Egret的開發(fā)環(huán)境
Egret基于TypeScript開發(fā)的,而TypeScript編譯工具tsc是基于Node.js 開發(fā)的。所以在安裝過程中,我們先需要對于基礎(chǔ)支持工具進(jìn)行安裝。2014-07-07
3分鐘快速搭建nodejs本地服務(wù)器方法運(yùn)行測試html/js
本篇文章主要介紹了3分鐘快速搭建nodejs本地服務(wù)器方法運(yùn)行測試html/js,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-04-04

