【发布时间】:2016-05-10 12:05:32
【问题描述】:
我只是在练习一些关于 child_process @the link 的节点 js 代码 我的节点版本是 Windows 7 上的 V5.2.0。
// 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) 我运行上面的代码,我得到了错误:写 EPIPE。我用谷歌搜索,我没有找到任何有用的答案。我只是nodejs的新手,我按照官方文档进行了一些修改,然后示例代码失败了。我发现如果我将块 C 中的代码注释掉,示例代码就可以了。所以我想知道为什么代码会抛出错误,如果 np.stdout/np.stderr 监听“数据”?
$ 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)我修改了master.js代码,运行如下代码:
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);
});
它会抛出一个错误:
np.send({Hello:"world"});
^
TypeError: np.send is not a function
我重新访问node js official doc,我没有发现 spawn() 和 fork() 有很大不同。所以我想知道为什么 np.send 不是一个函数?
有没有官方文档没有提到的几点?
【问题讨论】:
标签: javascript node.js child-process