Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom events with child processes in Node.js

Tags:

node.js

I'm currently using a child process in order to run some computational functions in a non-blocking way.

I'm running into an issue, where by I need to be able to tie the result of a computation back to the correct callback in the parent process. For example:

var cp = require('child_process');
var n = cp.fork(__dirname + '/child.js');

exports.evaluate = function(data, callback) {

    n.send({ data : data});

    n.once('message', function(result) {

        callback(result);

    }

}

The problem with this is example is that if one computation returns before another then it will not receive the correct results.

Is there any way to use a custom event name instead of 'message' in order to ensure that each time the evaluate function is called it creates a unique listener that will be removed once it is called?

How can I emit a custom event from with a child process?

like image 497
sicr Avatar asked Nov 04 '25 04:11

sicr


1 Answers

Create a a new EventEmitter with new events.EventEmitter. Then emit an event based on any message with eventType:"someType" you receive.

i.e. something like

 events = require("events")     
 emitter = new events.EventEmitter
 n.on("message", function(msg) { emitter.emit(msg.eventType,msg.body) })

Then bind listeners (with once or on) to that event emitter.

like image 121
Myrne Stol Avatar answered Nov 06 '25 01:11

Myrne Stol