In-process domain notifications
A component needs to notify multiple consumers when its state changes.
Node.js · Class
EventEmitter is Node.js’s base class for named, synchronous event dispatch. Register listeners with on() or once(), then trigger them with emit(), passing optional arguments.
EventEmitter provides named-event registration and emission. Listeners attached with on() or once() receive the arguments passed to emit(); dispatch is synchronous and follows registration order, while listener return values are ignored.
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 | The event name to subscribe to or emit; event names may be strings or symbols. |
listener | Function | The function invoked when the named event is emitted. |
...args | any | Values forwarded in order to each matching listener. |
The registration methods return the emitter for chaining; emit() returns true if the event had listeners and false otherwise.
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.once('ready', (name) => {
console.log(`${name} is ready`);
});
emitter.emit('ready', 'service');
emitter.emit('ready', 'service');The one-time listener runs only for the first emission, so the second emit produces no output.
A component needs to notify multiple consumers when its state changes.
A resource emits completion, close, or failure signals to coordinating code.
A one-time readiness signal must be consumed without manual cleanup.
A custom stream-like abstraction needs a familiar Node.js event interface.
EventEmitter is Node's class for objects that publish named events. Consumers register listener functions, and emit() invokes listeners for the matching event synchronously in registration order.
Follow-up: How would you prevent a listener from running more than once? Use once(), which removes the listener after its first invocation.
on() registers a listener for every future occurrence of an event, whereas once() registers a listener that is automatically removed after its first invocation. Both receive arguments supplied to emit().
Follow-up: What happens if the same function is registered repeatedly? Each registration is treated as a separate listener and can cause another invocation.
The special error event requires explicit handling: if it is emitted without an error listener, Node throws the error and exits the process. Register an error listener when the emitter may report failures.
Follow-up: Can error be emitted with arbitrary data? It should represent an Error condition; otherwise the emitted value is thrown as described by the API behavior.
EventEmitter.on()EventEmitter.once()EventEmitter.emit()EventEmitter.off()EventEmitter.removeListener()EventEmitter.addListener()EventEmitter.listenerCount()EventEmitter.listeners()