如何使用 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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值