如何在 node.js 子进程模块中将消息和标准输出从子进程传递到父进程?

How to pass messages as well as stdout from child to parent in node.js child process module?

我遇到了子进程模块的问题,特别是 child.spawn 和 child.fork。 我依赖 child_process.fork 的文档,它说:

This is a special case of the child_process.spawn() functionality for spawning Node.js processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in. See child.send(message, [sendHandle]) for details.

我在下面简化了我的问题:

parent.js 是:

var cp = require('child_process');
var n = cp.fork('./child.js');
n.send({a:1});
//n.stdout.on('data',function (data) {console.log(data);});
n.on('message', function(m) {
  console.log("Received object in parent:");
  console.log( m);
});

child.js 是:

process.on('message', function(myObj) {
  console.log('myObj received in child:');
  console.log(myObj);
  myObj.a="Changed value";
  process.send(myObj);
});
process.stdout.write("Msg from child");

不出所料。输出为:

Msg from child
myObj received in child:
{ a: 1 }
Received object in parent:
{ a: 'Changed value' }

我希望它与 parent.js 中未注释的注释行一起使用。换句话说,我想在父进程中的 n.stdout.on('data'... 语句中捕获子进程中的标准输出。如果取消注释,则会出现错误:

n.stdout.on('data',function (data) {console.log(data);});
    ^
TypeError: Cannot read property 'on' of null

我不介意使用任何子进程异步变体、exec、fork 或 spawn。有什么建议吗?

当您将选项对象传递给 fork() 时,您需要在选项对象上设置静默 属性,以便标准输入、标准输出和标准错误通过管道返回父进程。

例如var n = cp.fork('./child.js', [], { silent: true });

spawn('stdbuf', ['-i0', '-o0', '-e0', "./test-script" ]);