0

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

PirateApp
  • 5,433
  • 4
  • 57
  • 90
  • 2
    What exactly do you mean by 'a separate window'? Do you mean a different nodeJS process altogether? If this is the case then EventEmitter won't solve your problem as the EventEmitter events exist within a single node process. See this answer [here](https://stackoverflow.com/questions/17866864/inter-process-event-emitter-for-node-js) for a possible answer if I understood your question correctly. – MrfksIV Apr 22 '19 at 14:34

1 Answers1

1

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.

Andrew Yochum
  • 1,056
  • 8
  • 13