Today I Learned - Rocky Kev

TIL Node.js Event Emitter

POSTED ON:

TAGS:

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.

The Node.js Event emitter


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL keywords in package.json

Today I learned what keywords are in a package.json file! It's a collection of keywords about a module. Keywords can help identify a package, related modules and software, and concepts.

TIL functional async/await

PLACEHOLDER