The Node.js Event emitter
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 backend side, Node.js offers us the option to build a similar system using the events module.
This module, in particular, offers the EventEmitter class, which we'll use to handle our events.
You initialize that using
const class EventEmitter<T extends EventMap<T> = DefaultEventMap>EventEmitter = var require: NodeJS.Require
(id: string) => any
require('node:events');
const const eventEmitter: EventEmitter<DefaultEventMap>eventEmitter = new new EventEmitter<DefaultEventMap>(options?: EventEmitterOptions): EventEmitter<DefaultEventMap>EventEmitter();
This object exposes, among many others, the on and emit methods.
emitis used to trigger an eventonis used to add a callback function that's going to be executed when the event is triggered
For example, let's create a start event, and as a matter of providing a sample, we react to that by just logging to the console:
eventEmitter.on('start', () => {
var console: Consoleconsole.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)log('started');
});
When we run
eventEmitter.emit('start');
the event handler function is triggered, and we get the console log.
You can pass arguments to the event handler by passing them as additional arguments to emit():
eventEmitter.on('start', number: anynumber => {
var console: Consoleconsole.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)log(`started ${number: anynumber}`);
});
eventEmitter.emit('start', 23);
Multiple arguments:
eventEmitter.on('start', (start: anystart, end: anyend) => {
var console: Consoleconsole.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)log(`started from ${start: anystart} to ${end: anyend}`);
});
eventEmitter.emit('start', 1, 100);
The EventEmitter object also exposes several other methods to interact with events, like
once(): add a one-time listenerremoveListener()/off(): remove an event listener from an eventremoveAllListeners(): remove all listeners for an event
You can read more about these methods in the official documentation.