分叉子进程并注入依赖

11 dependency-injection process parent-child spawn node.js

我目前在一个阻塞的模块中有一个操作,所以我正在考虑把它变成一个我代替的子进程.

如果我想这样做,那么我当然需要修改我的模块的架构.该模块要求通过将模块作为函数调用来注入依赖项,并传入依赖项,如下所示:

var dependency = { name: "Bob" }
require('worker')(dependency)
Run Code Online (Sandbox Code Playgroud)

然后在我的worker模块中:

module.exports = function (dependency) {
  // Outputs { name: "Bob" }
  console.log(dependency)
}
Run Code Online (Sandbox Code Playgroud)

如何将此示例转换为分叉的子进程?

UpT*_*eek 23

使用.fork()时,您正在启动一个完全独立的进程,因此您无法在父进程和子进程之间传递引用(并且仅限于创建进程后的消息传递).

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

在顶层:

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

在工作过程中:

var name = process.argv[2]; //AFIAK elements 0 and 1 are already populated with env info
Run Code Online (Sandbox Code Playgroud)

更新

如果你真的想要去消息传递路径(如果你已经需要发送消息我会犹豫推荐),那么你可以区分这样的消息类型(可能有更优雅的方式):

在顶层:

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'}
Run Code Online (Sandbox Code Playgroud)

在工作过程中:

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.
    }
});
Run Code Online (Sandbox Code Playgroud)