Gary
Gary

Reputation: 2339

Nodejs events captured in any cluster process sent from cluster creating file

I am stuck here due to a simple event related issue. Here is the issue:

However, the events are not captured in any of the processes. I have tried making the event global and assign the event globally to a symbol but was unable to get it work/capture event as well.

Here is the codes:

cluster.js (child process creator)

...require > events.js...
... create cluster logic...
setInterval(function () {
 evt.emit('testTimer', {tester: 'test'});
 evt.tester();
}, 1000);

server.js (child process)

...require > events.js...
evt.on('testTimer', function (data) {

    console.log('Starting Sync ', data);
});

events.js (common file for events)

var util         = require("util");
var EventEmitter = require("events").EventEmitter;

function test () {
    EventEmitter.call(this);
}
test.prototype.tester = function (){
    this.emit('testTimer', {missed: 'this'})
}
util.inherits(test, EventEmitter);
module.exports = test;

Upvotes: 0

Views: 436

Answers (1)

robertklep
robertklep

Reputation: 203251

EventEmitter instances can't reach beyond the bounds of a process. If you want to communicate between parent and children, use worker.send():

// cluster.js
setInterval(function () {
  for (const id in cluster.workers) {
    cluster.workers[id].send({ type : 'testTimer', data : { tester : 'test' }});
  }
}, 1000);

// server.js
process.on('message', function(message) {
  if (message.type === 'testTimer') { 
    console.log('Starting Sync ', message.data);
  }
})

Upvotes: 4

Related Questions