在“结束”事件被触发之前写入stream

我正在使用几个child_process与一个Node.js父进程,我将所有从subprocessstderrpipe道到一个文件。

像这样:

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')发生之前在stream上触发。 事实上,在'end'被调用之前,似乎没有办法挂钩stream写入它; 好吧,其实我正在寻找一些方法来挂钩stream,以便在结束被调用之前,我可以至less写一次。

有没有办法做到这一点?

(另外,我也在寻找一种方法来将child_process stderrstream直接传递给文件,而不必先通过父进程,这可以通过调用process.stderr.pipe()在每个child_process

可能是这可能有所帮助:

这里当n.stdio[2]closures时,会自动closuresstrm 。 所以你可以用最后一块块手动结束strmstream。

 n.stdio[2] .on('end', function(){ strm.end('<<<<<< Suman runner end <<<<<<\n'); }) .pipe(strm, {end: false})