对于多个 child 进程,在 parent 进程中仅使用一个写入流
Use only one write stream in parent process for multiple child processes
假设我有多个 node.js child 进程,我希望它们 stdout/stderr 都写入同一个文件。
在 parent 过程中,理想情况下我可以为文件创建一个流,如下所示:
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'
以下似乎解决了这个问题,因此我们为每个 child 进程创建了一个新流:
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;
});
有没有办法 "keep the stream open" 即使 child 触发了结束事件?似乎没有必要为每个 child 进程创建一个新流。
要生成的流未关闭写入,您需要将 end
选项设置为 false
:
n.stdout.pipe(strm, {end: false});
n.stderr.pipe(strm, {end: false});
假设我有多个 node.js child 进程,我希望它们 stdout/stderr 都写入同一个文件。
在 parent 过程中,理想情况下我可以为文件创建一个流,如下所示:
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'
以下似乎解决了这个问题,因此我们为每个 child 进程创建了一个新流:
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;
});
有没有办法 "keep the stream open" 即使 child 触发了结束事件?似乎没有必要为每个 child 进程创建一个新流。
要生成的流未关闭写入,您需要将 end
选项设置为 false
:
n.stdout.pipe(strm, {end: false});
n.stderr.pipe(strm, {end: false});