gpt4 book ai didi

node.js - 在 'end' 事件触发之前写入流

转载 作者:太空宇宙 更新时间:2023-11-03 22:13:03 27 4
gpt4 key购买 nike

我正在将多个 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);

问题是在 process.on('exit') 发生之前,'end' 事件在流上触发。事实上,在调用“end”之前似乎没有办法 Hook 流来写入;好吧,实际上我正在寻找某种方法来 Hook 流,以便在调用 end 之前,我可以至少写入一次。

有办法做到这一点吗?

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

最佳答案

也许这可能有帮助:

这里,当 n.stdio[2] 关闭时,会阻止 strm 自动关闭。因此,您可以使用最后一 block block 手动结束 strm 流。

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

关于node.js - 在 'end' 事件触发之前写入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36759032/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com