TIL Node.js Event Emitter
POSTED ON:
TAGS: node javascript
Today I learned about the Node.js Event Emitter
This is kinda like the addEventListener()
for browser javascript.
If you worked with JavaScript in the browser, you know how much of the interaction of the user is handled through events: mouse clicks, keyboard button presses, reacting to mouse movements, and so on.
On the back-end side, Node.js offers us the option to build a similar system using the events module.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// Register a listener for the 'my-event' event
myEmitter.on('my-event', () => {
console.log('My event was emitted!');
});
// Emit the 'my-event' event
myEmitter.emit('my-event');
This works fine for a simple use case, but if you have multiple events and listeners, it can quickly become difficult to manage.
Related TILs
Tagged: node