如何在node.js子进程模块中将消息以及stdout从子进程传递给父进程?
我遇到了child-process模块的问题,特别是child.spawn和child.fork。 我靠child_process.fork的文档,它说的:如何在node.js子进程模块中将消息以及stdout从子进程传递给父进程?
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中的注释行一起使用uncommented。换句话说,我要赶在子进程标准输出的n.stdout.on(“数据” ......父进程声明如果我取消它,我得到一个错误:
n.stdout.on('data',function (data) {console.log(data);});
^
TypeError: Cannot read property 'on' of null
我不介意使用任何子进程异步变体,exec,fork或spawn。任何建议?
当您按顺序将它传递给fork()时,需要在options对象上设置silent属性为stdin,stdout和stderr返回父进程。
例如var n = cp.fork('./child.js', [], { silent: true });
顺便说一下,有没有什么方法可以读取这些日志并在使用'{silent:true}'的时候处理它们? – Kunok
有人可以请解释 - 为什么更喜欢'消息'监听器而不是'数据'而流...数据? – ymz