2015-11-02 6 views
8

子プロセスモジュール、特にchild.spawnとchild.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.

私は下に私の問題を単純化しています:私は言っている、child_process.forkのドキュメントに頼っています

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(「データ」...親プロセスにおける文で子プロセスで標準出力をキャッチしたい、私はそれのコメントを外した場合、私はエラーを取得:。

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

子プロセス非同期のバリエーション、exec、fork、またはspawnを使用しても構いません。ご提案は?

+0

誰かが説明してください - なぜストリーミング中に 'data'の代わりに' message'リスナーを好むのですか?data? – ymz

答えて

17

optionsオブジェクトをサイレントプロパティに設定する必要があります。 stdin、stdout、stderrが親プロセスにパイプラインされるようにします。

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

+0

ところで、これらのログを読んで、 '{silent:true}'を使ってそれらを処理する方法はありますか? – Kunok

関連する問題