在触发 'end' 事件之前写入流

Write to stream just before 'end' event is fired

我将几个 child_process 与一个 Node.js 父进程一起使用,并且我正在将所有 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' 被调用之前挂钩到流中写入它;好吧,实际上我正在寻找某种方式来挂接到流中,以便在调用结束之前,我可以至少写入一次。

有办法吗?

(顺便说一句,我也在寻找一种方法将 child_process stderr 流直接通过管道传输到文件,而无需先通过父进程。我可能可以通过简单地调用 process.stderr.pipe() 在每个 child_process)

这可能会有所帮助:

此处在 n.stdio[2] 关闭时防止 strm 自动关闭。所以你可以用最后一块块手动结束 strm 流。

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