2015-11-02 21 views
8

Sto riscontrando un problema con il modulo di elaborazione figlio, in particolare con child.spawn e child.fork. Sto contando sulla documentazione di child_process.fork, che dice:Come passare i messaggi e lo stdout da child a parent nel modulo del processo figlio node.js?

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.

Ho semplificato il mio problema di seguito:

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"); 

Come previsto. L'output è:

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

Voglio che funzioni con la riga commentata in parent.js non commentato. In altre parole, voglio prendere lo stdout nel processo figlio nel n.stdout.on ('dati' ... economico nel processo padre Se ho decommentarla, ottengo un errore:.

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

Non mi interessa usare nessuna delle variazioni asincrone del processo figlio, exec, fork o spawn Qualsiasi suggerimento?

+0

qualcuno può spiegare per favore - perché preferire il listener 'message' invece di 'data' durante lo streaming ... dati? – ymz

risposta

17

È necessario impostare la proprietà silent sull'oggetto options quando lo si passa a fork() nell'ordine per stdin, stdout e stderr per ottenere convogliato indietro al processo padre.

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

+0

A proposito, c'è un modo per leggere questi log ed elaborarli mentre si usa '{silent: true}'? – Kunok