Reputation: 163
I have three files:
my_emitter.js: instance of EventEmitter object to be shared (let's reference this as "myEmitter")
listener.js: where myEmitter.on() is called
registration_handler.js: where myEmitter.emit() is called
Listener is not receiving emitted event.
With the following code, I run node listener.js
first and then node registration_handler.js
second.
my_emitter.js:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
exports.emitter = myEmitter;
listener.js:
const emitterFile = require('./my_emitter');
const myEmitter = emitterFile.emitter;
myEmitter.on('test', (res) => {
console.log('worked!');
});
//within 5s, let's run registration_handler.js to emit the event
setTimeout(console.log, 5000, 'Done');
registration_handler.js:
const emitterFile = require('./my_emitter');
const myEmitter = emitterFile.emitter;
myEmitter.emit('test');
Expected:
$ node listener.js
worked!
Done
Actual:
$ node listener.js
Done
Upvotes: 2
Views: 2644
Reputation: 81
For it to work, you have to run them in the same Node.js process, for that, you can create a new file and require both your listener and emitter from there.
// another-file.js
require('./listener');
require('./registration_handler.js');
Running this new file should give you the expected results:
$ node another-file.js
worked!
Done
Upvotes: 4