如何使用 Node.js 开启多进程。
Node.js 以单线程的模式运行,使用事件驱动来处理异步 IO 并发(底层是多线程的线程池)。
然而,要是 Node 运行在一个多核 CPU 上,如何让 Node 充分利用多核的优势,并行地处理任务?我们可以使用多进程。由于 Node 的单线程特性,开启多进程后,Node 也获得多线程的执行能力。
Node 提供了 child_process 模块来创建子进程:
const child_process = require("child_process");
/*
Use exec.
*/
for (let i = 0; i < 3; i++) {
/* child_process.exec(command[, options], callback) */
/* callback <Function> called with the output when process terminates. */
const childProcessorExec = child_process.exec("node child.js " + i, function(error, stdout, stderr) {
if (error) {
console.error(`exec error: ${error}`);
return;
}
/* ES6 template literal */
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
// console.log("stdout: " + stdout);
// console.log("stderr: " + stderr);
});
childProcessorExec.on("exit", function(code) {
/* Any exit code other than 0 is considered to be an error. */
console.log("Child process exited, code: " + code);
});
}
我们能使用 exec
方法创建子进程,子进程的输出被缓存在 buffer 中。当子进程终止之后,exec
的回调函数得到调用,将 buffer 一次性全部输出。
另外,我们还可以使用 spawn
方法创建子进程:
/*
Use spawn.
*/
for (let i = 0; i < 3; i++) {
/* child_process.spawn(command[, args][, options]) */
/* args is an array of string */
const childProcessorSpawn = child_process.spawn("node", ["child.js", i]);
childProcessorSpawn.stdout.on("data", (data) => {
console.log(`stdout: ${data}`);
});
childProcessorSpawn.stderr.on("data", (data) => {
console.log(`stderr: ${data}`);
});
childProcessorSpawn.on("close", function(code) {
/* Any exit code other than 0 is considered to be an error. */
console.log("Child process closed, code: " + code);
});
}
使用spawn
可以实现一有数据就输出,而不必等到进程终止。
参考链接:Node child_process 模块源码,How to create threads in nodejs in Stack Overflow