Node.js 子进程 — 执行系统命令
用 child_process 模块执行 shell 命令、Python 脚本等外部程序 · 难度:高级 · +20XP
child_process 模块
child_process 让你在 Node.js 中执行外部命令——运行 shell 命令、调用 Python 脚本、执行其他可执行程序。
这在你需要调用系统工具(如 git、ffmpeg、imagemagick)时非常有用。
exec vs spawn
| exec | spawn |
|---|---|
| 适合短命令,一次性返回所有输出 | 适合长时间运行的进程,流式返回输出 |
| 有默认缓冲区大小限制(200KB) | 无缓冲区限制 |
| 用法简单 | 更灵活 |
exec 用法
const { exec } = require("child_process");
// 执行 shell 命令
exec("ls -la", (error, stdout, stderr) => {
if (error) {
console.error("执行失败:", error);
return;
}
console.log("输出:", stdout);
});
spawn 用法(推荐:流式处理)
const { spawn } = require("child_process");
const child = spawn("node", ["--version"]);
child.stdout.on("data", (data) => {
console.log(输出: ${data});
});
child.stderr.on("data", (data) => {
console.error(错误: ${data});
});
动手试试
- 用 exec 执行 dir(Windows)或 ls(Linux)命令
- 用 spawn 执行 node --version 获取 Node 版本