Node.js 不僅能構建高性能 Web 服務,其 child_process 模組還能讓 JavaScript 直接調用 Linux Shell 命令,實現自動化運維、文件處理、進程管理等任務。本文通過實例詳解 exec、execFile、spawn 三種核心 API 的用法與區別。

| 方法 | 適用場景 | 特點 |
|---|---|---|
exec(command, callback) | 簡單命令、獲取完整輸出 | 緩衝輸出、有大小限制、適合短任務 |
execFile(file, args, callback) | 直接執行可執行文件(無 Shell 解析) | 較輕量、避免 Shell 注入風險 |
spawn(command, args) | 長時間運行、大數據流、交互式程序 | 流式處理、內存效率高、支持管道 |
const { exec } = require('child_process');
exec('pwd', (error, stdout, stderr) => {
if (error) {
console.error(`執行錯誤: ${error}`);
return;
}
console.log(`標準輸出: ${stdout}`);
console.error(`標準錯誤: ${stderr}`);
});
注意:exec 默認使用 /bin/sh 解析命令,支持管道、重定向等 Shell 特性,但需防範命令注入(避免拼接不可信輸入)。
const { execFile } = require('child_process');
// 執行 Shell 腳本
execFile('./deploy.sh', ['prod'], (error, stdout, stderr) => {
if (error) throw error;
console.log('部署輸出:', stdout);
});
// 執行二進制程序(如壓縮)
execFile('tar', ['-czf', 'backup.tar.gz', '/var/www'], (err, out, errout) => {
if (err) console.error('壓縮失敗:', err);
else console.log('壓縮完成');
});
優勢:繞過 Shell,參數以數組傳遞,安全性更高;適用於已知路徑的腳本或二進制文件。
const { spawn } = require('child_process');
const tail = spawn('tail', ['-f', '/var/log/nginx/access.log']);
tail.stdout.on('data', (chunk) => {
process.stdout.write(`[實時日志] ${chunk}`);
});
tail.stderr.on('data', (data) => {
console.error(`tail 錯誤: ${data}`);
});
tail.on('close', (code) => {
console.log(`進程退出碼: ${code}`);
});
關鍵點:spawn 返回流對象,適合持續輸出的命令(tail -f、ping、視頻轉碼等),避免緩衝區溢出。
// utils/cmd.js
const { exec, spawn } = require('child_process');
/** 返回 Promise 的 exec 封裝 */
function runCmd(cmd, options = {}) {
return new Promise((resolve, reject) => {
exec(cmd, options, (err, stdout, stderr) => {
if (err) reject({ err, stdout, stderr });
else resolve({ stdout, stderr });
});
});
}
/** 流式輸出封裝 */
function streamCmd(cmd, args, onData) {
const proc = spawn(cmd, args);
proc.stdout.on('data', onData);
return new Promise((resolve) => proc.on('close', resolve));
}
module.exports = { runCmd, streamCmd };
execFile 或 spawn 的數組參數形式。exec(cmd, { timeout: 5000, maxBuffer: 1024*1024 })。exec,對參數進行 shell-escape 處理。掌握 Node.js 執行系統命令的各種姿勢,能讓前端工程師、全棧開發者輕鬆實現自動化部署、服務器監控、文件批量處理等運維任務,極大提升開發效率。
Linux xhost 命令详解:X Server 访问控制与远程图形应用授权
Linux 系統 sync 指令詳細解析:確保資料真正寫入磁碟
修復 Ubuntu apt-get 提示 Unable to locate package 錯誤只需執行 apt-get update
Ubuntu 編譯安裝 FFmpeg 完整教學:從 yasm 依賴到安裝驗證
Linux find + crontab 實現日誌定期遷移:按時間/大小篩選自動歸檔
關閉 Firefox 預測性連線保護隱私:about:config 設定 network.http.speculative-parallel-limit = 0