【发布时间】:2016-04-21 03:24:15
【问题描述】:
我在 Node.js 父进程中使用了几个 child_process,并且我正在将所有 stderr 从子进程传送到一个文件。
像这样:
const strmPath = path.resolve(projRoot + '/suman/stdio-logs/runner-stderr.log');
const strm = fs.createWriteStream(strmPath);
//before I call pipe I write some stuff to the log file
strm.write('\n\n>>> Suman start >>>\n');
strm.write('Beginning of run at ' + Date.now() + ' = [' + new Date() + ']' + '\n');
strm.write('Command = ' + JSON.stringify(process.argv) + '\n');
// when the parent process exits, I want to write one more line to the log file
process.on('exit', function (code, signal) {
strm.write('<<<<<< Suman runner end <<<<<<\n');
});
在父进程中,我将数据通过管道传输到文件,如下所示:
const n = cp.fork(path.resolve(__dirname + '/run-child.js'), argz, {silent: true});
n.on('message', function (msg) {
handleMessage(msg, n);
});
n.stdio[2].setEncoding('utf-8');
n.stdio[2].pipe(strm);
问题是 'end' 事件在 process.on('exit') 发生之前在流上触发。事实上,似乎没有办法在调用“end”之前挂钩到流中写入;好吧,实际上我正在寻找某种方式来挂钩流,以便在调用 end 之前,我可以至少写入一次。
有没有办法做到这一点?
(顺便说一句,我也在寻找一种将 child_process stderr 流直接传输到文件的方法,而不必先通过父进程。这我可以通过在每个 @987654324 中简单地调用 process.stderr.pipe() 来完成@)
【问题讨论】: