节点:在快速退出事件后读取 spawn stderr/stdout?

srl*_*rlm 5 spawn node.js

我正在使用 Nodespawn创建一个新进程。有时,此过程会很快退出,并在 stderr 上显示错误代码和消息。似乎 stderr 在这种快速转变中迷失了方向。我试过这个:

    reader.stderr.on('data', function (buf) {
        console.log('stderr message: ' + buf);
    });

    reader.on('exit', function (code, signal) {
        console.log('Exit');
    });
Run Code Online (Sandbox Code Playgroud)

输出:

   Exit
   stderr message: ERROR: Missing required option for command.
Run Code Online (Sandbox Code Playgroud)

我也尝试在exit听众中阅读它,但没有运气:

     reader.on('exit', function (code, signal) {
        console.log('Exit');
        console.log('stderr: ' + reader.stderr.read());
    });
Run Code Online (Sandbox Code Playgroud)

输出:

    Exit
    stderr: null
Run Code Online (Sandbox Code Playgroud)

因此,问题似乎是 stderr 输出太慢,并且在我需要该信息的退出事件之后延迟。我怎样才能解决这个问题?

log*_*yth 7

取自child_process 文档exit

请注意,子进程 stdio 流可能仍处于打开状态。

然后他们描述了该close事件:

当子进程的 stdio 流全部终止时,会发出此事件。这与“退出”不同,因为多个进程可能共享相同的 stdio 流。

所以看起来你应该使用close,而不是exit