Node.js 子進程運行CMD命令詳解
本文將介紹如何在 Node.js 中通過 child_process 模塊使用 exec、execFile 和 spawn 三種方法來創(chuàng)建子進程運行cmd運行,并通過示例說明了每種方法的參數(shù)和輸出處理方式。
在介紹子進程前先創(chuàng)建一個node腳本名為printArgs.js,該腳本的作用是接收參數(shù)并將參數(shù)輸出。后續(xù)將使用node子進程調用該腳本。腳本代碼如下:
// 獲取命令行參數(shù),process.argv 是一個數(shù)組,其中包含了命令行參數(shù)
// 第一個元素是 node 的路徑,第二個元素是腳本文件的路徑,從第三個元素開始是用戶傳入的參數(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ù),并延遲打印每個參數(shù),模擬異步處理流程。
- process.argv:Node.js 中獲取命令行參數(shù)的數(shù)組:
- argv[0]: Node 可執(zhí)行文件路徑
- argv[1]: 當前執(zhí)行的腳本路徑
- argv[2...]: 用戶輸入的參數(shù)
- setTimeout:每個參數(shù)延遲 (index + 1) * 1000 毫秒后打印
創(chuàng)建index.js腳本,引入了 Node.js 的 child_process 模塊中的三個方法,下面將分別介紹這三個方法的區(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í)行錯誤:${error}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
}
console.log(`stdout: ${stdout}`);
}
);
execChild.on("close", (code) => {
console.log(`子進程退出,退出碼$[code]`);
})方法說明: exec(command[, options][, callback])
適用場景:執(zhí)行一條 shell 命令并一次性獲取輸出(適合小輸出量任務),即運行printArgs腳本后將等待3秒一次性輸出 aaa bbb ccc
參數(shù):
- command:完整的 shell 命令字符串。
- encoding: 設置輸出編碼,如 "utf8"。
- callback:回調函數(shù),獲取 error、stdout(標準輸出)、stderr(錯誤輸出)。
- execChild.on("close", callback):監(jiān)聽子進程關閉事件,獲取退出碼。
2.execFile
let fileChild = execFile(
"node",
["printArgs.js", "aaa", "bbb", "ccc"],
{ encoding: "utf8", cwd: "" }, //cwd為工作目錄
(error, stdout, stderr) => {
if (error) {
console.error(`執(zhí)行出錯: ${error}`);
return;
}
if (stderr) {
console.error(`stderr: ${stderr}`);
}
console.log(`stdout: ${stdout}`);
}
);
fileChild.on("close", (code) => {
console.log(`子進程退出,退出碼$[code]`);
});方法說明 execFile(file[, args][, options][, callback])
適用場景:直接運行某個可執(zhí)行文件,代碼中使用node執(zhí)行printArgs腳本,等待3秒后一次性輸出 aaa bbb ccc
參數(shù):
- file: 可執(zhí)行文件或腳本(如 node)。
- args: 參數(shù)數(shù)組,即["printArgs.js", "aaa", "bbb", "ccc"]
- cwd: 工作目錄(空字符串為當前目錄)。
- encoding: 輸出編碼。
- callback: 同上,獲取輸出結果。
- fileChild.on("close", callback):監(jiān)聽子進程關閉事件,獲取退出碼。
3.spawn
const spawnChild = spawn("node", ["./printArgs.js", "aaa", "bbb", "ccc"], {
shell: true,
}); // 在 Windows 上執(zhí)行 CMD 命令時,通常需要設置 { 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(`子進程退出,退出碼 $[code]`);
})方法說明 spawn(command[, args][, options])
適用場景:持續(xù)處理大數(shù)據(jù)流、監(jiān)聽標準輸出/錯誤(如服務器日志),代碼中調用printArgs腳本將每隔1秒輸出內容
參數(shù):
- command: 執(zhí)行命令。
- args: 參數(shù)數(shù)組,即["./printArgs.js", "aaa", "bbb", "ccc"]
- shell: true:在 Windows 下推薦啟用,執(zhí)行 shell 命令時必要。
- spawnChild.on實時監(jiān)聽標準輸出/錯誤。
總結對比
| 方法 | 是否用 shell | 適用場景 | 是否支持大數(shù)據(jù)流 | 回調/事件模型 |
|---|---|---|---|---|
| exec | 是 | 簡單命令 + 小輸出 | 否 | 回調函數(shù) |
| execFile | 否 | 執(zhí)行文件 + 安全性要求高 | 否 | 回調函數(shù) |
| spawn | 否(可選) | 大數(shù)據(jù)流 / 持續(xù)輸出任務 | 是 | 事件監(jiān)聽 |
到此這篇關于Node.js 子進程運行CMD命令詳解的文章就介紹到這了,更多相關Node.js 子進程運行CMD內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
一會帶你學會用Webpack搭建開發(fā)環(huán)境并打包代碼
這篇文章主要給大家介紹了關于如何用Webpack搭建開發(fā)環(huán)境并打包的相關資料,webpack是一個現(xiàn)代JavaScript應用程序的靜態(tài)模塊打包器(module bundler),需要的朋友可以參考下2023-08-08
Windows 系統(tǒng)下安裝和部署Egret的開發(fā)環(huán)境
Egret基于TypeScript開發(fā)的,而TypeScript編譯工具tsc是基于Node.js 開發(fā)的。所以在安裝過程中,我們先需要對于基礎支持工具進行安裝。2014-07-07
3分鐘快速搭建nodejs本地服務器方法運行測試html/js
本篇文章主要介紹了3分鐘快速搭建nodejs本地服務器方法運行測試html/js,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-04-04

