【问题标题】:Use only one write stream in parent process for multiple child processes多个子进程在父进程中只使用一个写入流
【发布时间】:2017-04-15 20:09:11
【问题描述】:

假设我有多个 node.js 子进程,我希望它们的 stdout/stderr 都写入同一个文件。

在父进程中,理想情况下我可以为文件创建一个流,如下所示:

const cp = require('child_process');
const strm = fs.createWriteStream('bar.log');

async.each([1,2,3], function(item, cb){

 const n = cp.spawn('node', ['foo' + item + '.js']);

 n.stdout.pipe(strm);
 n.stderr.pipe(strm);

 n.on('close', cb);

}, function(err){
 if(err) throw err;
});

很可能会发生错误:

Error: write after 'end'

以下似乎解决了这个问题,我们为每个子进程创建一个新流:

const cp = require('child_process');

async.each([1,2,3], function(item, cb){

 const n = cp.spawn('node',['foo' + item + '.js']);

  //create a new stream for every child process...
 const strm = fs.createWriteStream('bar.log');

 n.stdout.pipe(strm);
 n.stderr.pipe(strm);

 n.on('close', cb);

}, function(err){
    if(err) throw err;
});

即使孩子触发结束事件,有没有办法“保持流打开”?似乎没有必要为每个子进程创建一个新流。

【问题讨论】:

    标签: node.js stream node.js-stream


    【解决方案1】:

    对于未关闭写入的结果流,您需要将end 选项设置为false

     n.stdout.pipe(strm, {end: false});
     n.stderr.pipe(strm, {end: false});
    

    【讨论】:

    • 确认这有效,必须将其用于其他用途,谢谢!
    猜你喜欢
    • 2017-09-19
    • 1970-01-01
    • 2016-07-27
    • 2014-05-11
    • 2017-06-29
    • 2016-08-20
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    相关资源
    最近更新 更多