Application event bus
Coordinate internal application components without tightly coupling them to each other.
Node.js · Module
Node.js's node:events module provides EventEmitter for named, synchronous notifications. Register persistent or one-time listeners, emit events with arguments, and remove listeners when they are no longer needed.
The node:events module provides EventEmitter, whose instances associate named events with listener functions. Register listeners with on() or once(), trigger them with emit(), and remove them with off() or removeListener(); listeners run synchronously in registration order.
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.on(eventName, listener);
emitter.once(eventName, listener);
emitter.emit(eventName, ...args);| Name | Type | Description |
|---|---|---|
eventName | string | symbol | Event name or event key identifying the notification channel. |
listener | (...args: any[]) => void | Function invoked when the event is emitted. |
args | any[] | Values forwarded to listeners by emit(). |
EventEmitter methods such as on(), once(), off(), and removeListener() return the emitter for chaining; emit() returns a boolean indicating whether listeners were called.
import { EventEmitter } from "node:events";
const bus = new EventEmitter();
bus.once("ready", (name) => {
console.log(`${name} is ready`);
});
bus.on("message", (text) => {
console.log(text);
});
bus.emit("ready", "worker");
bus.emit("ready", "worker");
bus.emit("message", "processed");Creates an emitter, registers a one-time listener and a regular listener, then emits events with arguments.
Coordinate internal application components without tightly coupling them to each other.
Notify consumers about lifecycle transitions such as startup, shutdown, or connection changes.
React to stream, server, or resource events exposed by Node.js APIs.
EventEmitter is the class exposed by node:events for objects that publish named events. on() attaches listeners, and emit() invokes listeners for the selected event.
Follow-up: How are listeners scheduled? They run synchronously, in the order they were registered, unless a listener explicitly defers its own work.
on() registers a listener that remains attached for every matching emission. once() removes its listener after the first matching event, so it handles at most one occurrence.
Follow-up: When would you choose once()? Use it for one-time lifecycle events such as initialization or a first connection.
emit() invokes listeners for the named event and can pass arguments to them. Listener return values are not used by EventEmitter.
Follow-up: How should failures be handled? Attach an error listener because an emitted error without a registered error handler is special and can terminate the process.
EventEmitterEventEmitterAsyncResourceEventEmitter.onEventEmitter.onceEventEmitter.emitEventEmitter.offEventEmitter.removeListenerevents.once