Ich habe ein Problem mit Kind-Prozess-Modul, speziell mit child.spawn und child.fork. ich auf der Dokumentation von child_process.fork verlasse mich, die sagt:Wie übergibt man im untergeordneten Prozessmodul node.js sowohl Nachrichten als auch stdout von Kind an Eltern?
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.
ich mein Problem unten vereinfacht:
parent.js ist:
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 ist:
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");
Wie erwartet. Die Ausgabe ist:
Msg from child
myObj received in child:
{ a: 1 }
Received object in parent:
{ a: 'Changed value' }
Ich möchte es mit der kommentierten Zeile in parent.js unkommentiert arbeiten. Mit anderen Worten, ich möchte in der n.stdout.on (‚data‘ ... Anweisung in dem Eltern-Prozess den stdout in dem untergeordneten Prozess fangen Wenn ich es Kommentar-, ich einen Fehler.
n.stdout.on('data',function (data) {console.log(data);});
^
TypeError: Cannot read property 'on' of null
Es macht mir nichts aus, asynchrone Child-Process-Varianten, exec, fork oder spawn zu verwenden. Irgendwelche Vorschläge?
kann jemand bitte erklären - warum zu bevorzugen "message" listener statt "daten" beim streamen ... daten? – ymz