分叉一个subprocess并注入依赖

我目前有一个模块是阻塞的操作,所以我正在考虑把它变成一个subprocess,而不是叉。

如果我想这样做,那么我当然需要修改我的模块的架构。 该模块要求dependency injection通过调用模块作为一个函数,传入依赖关系,如下所示:

var dependency = { name: "Bob" } require('worker')(dependency) 

然后在我的worker模块中:

 module.exports = function (dependency) { // Outputs { name: "Bob" } console.log(dependency) } 

我怎样才能把这个例子变成一个分叉的subprocess呢?

当使用.fork()函数时,你正在build立一个完全独立的进程,所以你不能在父进程和subprocess之间传递引用(并且在创build进程后仅限于消息传递)。

不需要消息传递的方法是在分支进程时传递参数(在数组中)。 虽然我相信你必须坚持使用简单的string/数字值(但是看起来这对于你来说可能足够了)。 例如。:

在顶层:

 var name = 'bob' var args = [name]; var childProcess = require('child_process').fork(__dirname + '/worker', args); 

在工作stream程中:

 var name = process.argv[2]; //AFIAK elements 0 and 1 are already populated with env info 

更新

如果你真的想去消息路由(如果你已经需要发送消息,我会毫不犹豫地推荐),那么你可以区分消息的types(可能有更优雅的方式):

在顶层:

 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'} 

在工作stream程中:

 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. } }); 

在主要模块中:

 var dependency = {message: 'hello there'}; var args = [JSON.stringify(dependency)]; var child = require('child_process').fork('worker', args); child.send('sayhello'); child.send('exit'); 

而在subprocess模块(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(); }); 

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