Search code examples
node.jseventseventemitter

EventEmitter event not received


I have 3 files

a.js the shared EventEmitter module

const EventEmitter = require('events');

const myEmitter = new EventEmitter();

module.exports = myEmitter;

b.js the publisher

const myEmitter = require('./a');

// Perform the registration steps

let user = 1;

setInterval(() => {
    myEmitter.emit('user-registered', user);    
    user++;
}, 1000);

// Pass the new user object as the message passed through by this event.

c.js the subscriber

const myEmitter = require('./a');

myEmitter.on('user-registered', (user) => {
  // Send an email or whatever.
  console.log(user);

});

When I run b.js or the publisher, the events are being published continuously but when I run c.js in a separate window, it immediately quits execution, how do I make this work with the subscriber actually listening to the publisher


Solution

  • The trouble you're having is that you're trying to publish events in one process, and listen for them in a separate process. The core Events API is not intended for this kind of interprocess communication.

    Adjusting your example to work would best be done by changing a.js to:

    const EventEmitter = require('events');
    const publisher = require('./b');
    const subscriber = require('./c');
    
    const myEmitter = new EventEmitter();
    
    module.exports = myEmitter;
    

    And then run a.js alone. This will run both publisher and subscriber in the same process.