Node.js 拦截另一个进程的输出

Node.js intercept output of another process

我正在尝试从 运行 Node.js 进程启动一些进程。 问题是,这些必须从脚本启动,并像这样使用 exec:

exec("./scripts/run.sh",(err, stdout, stderr)  => {
if (err) {
  console.error(err);
  return;
}
  this.logs = this.logs.unshift(timestamp() + stdout);
  this.errorlogs = this.logs.unshift(timestamp() + stderr);
});

不重定向我需要的输出。 Fork 似乎只适用于 Node.js 个进程,而这些不是。

这些进程工作得很好,并且作为主进程的子进程运行。我只需要实际获得 stdout 和 stderr 输出。 有什么建议吗?

child_process.exec() 仅在执行进程终止后运行回调函数一次。如果您希望进程的 stdout 和 stderr 的增量数据仍然是 运行,请使用 child_process.spawn() 并设置 options.stdio 属性以使进程的 stdout 和 stderr 对父进程可用。

child_process.spawn() returns 一个 ChildProcess 对象。要收集流程的输出,您可以为该对象的 stdoutstderr 流建立数据处理程序。您还应该为进程启动失败时触发的 error 事件和这些流关闭且进程终止时触发的 close 事件建立处理程序。

它将看起来像这样:

  child = spawn("./scripts/run.sh", 
                [],
                {stdio: ['ignore', 'pipe', 'pipe']});

  child.on('error', (err) => }
      console.log('child launch failed: ', err);
  });

  child.on('close', (code) => {
      console.log('child ended: ', code);
  });

  child.stdout.on('data', (outdata) => {
      this.logs = this.logs.unshift(timestamp() + outdata);
  });

  child.stderr.on('data', (errdata) => {
      this.errorlogs = this.logs.unshift(timestamp() + errdata);
  });

血淋淋的细节在 Node.js 文档中 https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_child_process_spawn_command_args_options and https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_class_childprocess