I just practise some node js code about child_process @the link My node version is V5.2.0 on windows 7.
// master.js
var cp=require("child_process");
var np=cp.fork("./console.js"); // line B
// block C
np.stdout.on("data",function(data){
console.log("child process output:"+data);
});
np.stderr.on("data", function(err){
console.log("child process output error:"+err);
});
np.on("close", function () {
console.log("child process exit");
});
// end of block C
np.send({Hello:"world"});
np.on("message",function(msg){
console.log("parent process got a msg:",msg);
});
// console.js
#!/usr/bin/env node
var aa=1;
console.log("The aa is :"+aa);
process.on("message", function (m) {
console.log("child process got message:",m);
});
process.send({foo:"bar"});
1) I run above code ,I got the error: write EPIPE. I googled and I don't find any useful answer. I just a new to nodejs, I follow the official doc and do a little modification, then the sample code failes. I find that if I comment out the code in block C, the sample code is ok. So I wonder why the code throw error, if np.stdout/np.stderr listens to 'data'?
$ The aa is :1
events.js:142
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at exports._errnoException (util.js:856:11)
at process.target._send (internal/child_process.js:607:18)
at process.target.send (internal/child_process.js:508:19)
at Object.<anonymous> (D:\Practice\..\console.js:
11:9)
at Module._compile (module.js:399:26)
at Object.Module._extensions..js (module.js:406:10)
at Module.load (module.js:345:32)
at Function.Module._load (module.js:302:12)
at Function.Module.runMain (module.js:431:10)
at startup (node.js:141:18)
2) I modify the master.js code, run the code like below:
var cp=require("child_process");
var np=cp.spawn("node", ["./console.js"]);
np.send({Hello:"world"});
np.on("message",function(msg){
console.log("parent process got a msg:",msg);
});
It throws an error:
np.send({Hello:"world"});
^
TypeError: np.send is not a function
I revisit the node js official doc, I don't find the spawn() and fork() are very different. So I wonder why np.send is not a function?
Are there some points the official doc doesn't mention?