node 中 exec,fork 与 spawn 有何区别
Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 302
Author 回答者: maya1900
- child_process.spawn():适用于返回大量数据
const spawn = require("child_process").spawn; const child = spawn("ls", ["-l"], { cwd: "/usr" }); child.stdout.pipe(process.stdout); console.log(process.pid, child.pid);
- child_process.exec():执行命令,有回调函数获知进程情况,可设置超时
const exec = require("child_process").exec; exec(`node -v`, (err, stdout, stderr) => { console.log({ err, stdout, stderr }); // { err: null, stdout: 'v16.14.2\n', stderr: '' } });
- child_process.execFile():执行可执行文件
const execFile = require("child_process").execFile; execFile("node", ["-v"], (error, stdout, stderr) => { console.log({ error, stdout, stderr }); });
- child_process.fork():执行js文件,衍生新的进程,每个进程都有自己的实例、内存
const fork = require("child_process").fork; fork("./worker.js");