[英]Node.JS Forked Pipe
我試圖根據此stackoverflow問題上發布的示例將node.js模塊分叉為子進程。 叉本身的工作,但我遇到的問題是,節點正在嘗試加入.on('data')
和.on('exit')
的前fork('./DaemonSerial.js'
填充tChild
var fork = require('child_process').fork;
// Start Serial Daemon/s
var tChild = fork('./DaemonSerial.js', [], {
stdio: 'pipe'
});
tChild.stdin.on('data', function(data) {
// output from the child process
console.log("./DaemonSerial.js >>> " + data)
});
EdgeMaster.Children[tChild.pid] = tChild;
tChild.on('exit', function(d) {
console.log("./DaemonSerial.js >>> "+ tChild.pid + ' Exited:'+ d);
delete EdgeMaster.Children[tChild.pid]
});
我也在其他地方遇到過這個問題,並且我確定應該有一種強制執行此do THIS then THAT
的方法,即使函數本身沒有回調也是如此。 child_process.fork(modulePath, [args], [options])
上nodejs.org/api/child_process.html沒有列出的回調。
想法?
編輯:我寫了一個新的腳本forktest.js
以排除我的腳本的其他部分可能導致問題的任何可能性。 forktest.js
完全如下:
var fork = require('child_process').fork;
var ForkDict = {};
function forkit(aPath){
tChild = fork( aPath, [], {stdio: 'pipe'});
ForkDict[tChild.pid] = tChild;
ForkDict[tChild.pid].path = aPath;
tChild.stdout.on('data', function(data) {
// output from the child process
console.log( this.path +'>>> '+ data);
}.bind(this));
tChild.on('exit', function(d) {
console.log( this.path +'>>> Exited:'+ d);
delete ForkDict[tChild.pid]
}.bind(this));
}
forkit('./DaemonSerial.js');
控制台的錯誤如下:
pi@raspberrypi ~ $ node forktest.js
/home/pi/forktest.js:9
tChild.stdout.on('data', function(data) {
^
TypeError: Cannot call method 'on' of null
at forkit (/home/pi/forktest.js:9:19)
at Object.<anonymous> (/home/pi/forktest.js:19:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
fork
是異步的,但它的返回值不是異步填充的。 它返回一個繼承自EventEmitter的ChildProcess實例。 EventEmitter通常用於異步任務,但是在發生某些事件而不是使用回調時會收到事件。 就像在文檔中說的那樣:
這些方法遵循常見的異步編程模式(接受回調或返回EventEmitter)。
在第一個例子中:
fork
沒有stdio
選項。 你應該使用silent: true
; 調用spawn
並將stdio
選項設置為“pipe”。 tChild.stdin.on('data', ...
您可能想要使用stdout
。 似乎stdin
和stdout
可以為null
具體取決於您是否使用silent: true
或不使用。 請參閱fork
文檔中的options.silent
:
Boolean
如果為true,則子項的stdin,stdout和stderr將通過管道傳遞給父項,否則它們將從父項繼承,有關詳細信息,請參閱spawn()的stdio的“管道”和“繼承”選項(默認為false
)
所以數據只是轉到主腳本的stdout
。 你可以解決這個問題(注意你的stdio
選項沒有做任何事情):
tChild = fork( aPath, [], {silent: true});
正如我之前所說,你需要在stdout
上監聽data
事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.