[英]Fork a child process and inject dependency
我目前在一個阻塞的模塊中有一個操作,所以我正在考慮把它變成一個我代替的子進程。
如果我想這樣做,那么我當然需要修改我的模塊的架構。 該模塊要求通過將模塊作為函數調用來注入依賴項,並傳入依賴項,如下所示:
var dependency = { name: "Bob" }
require('worker')(dependency)
然后在我的worker
模塊中:
module.exports = function (dependency) {
// Outputs { name: "Bob" }
console.log(dependency)
}
如何將此示例轉換為分叉的子進程?
使用.fork()時,您正在啟動一個完全獨立的進程,因此您無法在父進程和子進程之間傳遞引用(並且僅限於創建進程后的消息傳遞)。
不需要消息傳遞的方法是在分叉進程時傳遞參數(在數組中)。 雖然我相信你必須堅持使用簡單的字符串/數字值(但看起來這對你來說可能已經足夠了)。 例如。:
在頂層:
var name = 'bob'
var args = [name];
var childProcess = require('child_process').fork(__dirname + '/worker', args);
在工作過程中:
var name = process.argv[2]; //AFIAK elements 0 and 1 are already populated with env info
更新
如果你真的想要去消息傳遞路徑(如果你已經需要發送消息我會猶豫推薦),那么你可以區分這樣的消息類型(可能有更優雅的方式):
在頂層:
var childProcess = require('child_process').fork(__dirname + '/worker');
childProcess.send({msgtype:'dependencies', content:dependencies});
//Then to send 'normal' message:
childProcess.send({msgtype:'myothermessagetype', content:'some content'}
在工作過程中:
process.on('message', function(msg){
if(msg.mtype == 'dependencies') {
var dependencies = msg.content;
//Do something with dependencies
} else if(msg.mtype == 'myothermessagetype') {
var normalmessage = msg.content;
//Do something in response to normal message.
}
});
a.js
var fork = require ("child_process").fork;
var child;
var init = false;
var m = module.exports = {};
m.init = function (o){
if (init) return;
init = true;
child = fork (__dirname + "/child");
child.send ({ init: o });
};
m.print = function (o){
if (!init) return;
child.send ({ msg: o });
};
m.uninit = function (){
if (!init) return;
child.on ("exit", function (){
init = false;
});
child.kill ();
};
child.js
var dependency;
var print = function (o){
console.log (o + dependency.name);
};
process.on ("message", function (o){
if (o.init){
dependency = o.init;
}else{
print (o.msg);
}
});
b.js
var a = require ("./a");
a.init ({ name: "asd" });
a.print ("hi, ");
setTimeout (function (){
a.uninit ();
}, 1000);
印刷品:嗨,asd
在主模塊中:
var dependency = {message: 'hello there'};
var args = [JSON.stringify(dependency)];
var child = require('child_process').fork('worker', args);
child.send('sayhello');
child.send('exit');
並在子進程模塊(worker.js)中:
var dependency = JSON.parse(process.argv[2]);
process.on('message', function(m){
if(m == 'sayhello') console.log(dependency.message);
else if(m == 'exit') process.exit();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.