2016-12-01 65 views
0

假设我有多个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; 
}); 

即使孩子开始结束活动,是否有办法“保持开放状态”?似乎没有必要为每个子进程创建一个新的流。

回答

1

向所得到的流没有关闭写你所需要的end选项设置为false

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

不错,希望这个作品,谢谢! –

+0

@AlexanderMills你说什么?有用? –

+0

确认这个工作,不得不用它来做别的,谢谢! –