【发布时间】: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