EventEmitter from node:events is a class that lets objects send named events to listeners. It implements the observer pattern: listeners subscribe to an event, and the emitter calls them when the event happens. Much of Node's core is built on it. Streams, HTTP servers, sockets and process are all emitters.
The main methods:
on(name, listener)registers a listener. Its alias isaddListener.onceregisters a listener that is removed after the first call.emit(name, ...args)calls all listeners for that event.off(aliasremoveListener) removes one listener.removeAllListenersremoves all of them.prependListeneradds a listener to the front of the list.listenerCountreturns how many listeners are attached.
emit calls the listeners synchronously, in the order they were registered. It returns true if there were any listeners.
The error event is special. If you emit error and no listener is attached, Node throws the error.
EventEmitterimplements the observer pattern and is the base of streams, servers andprocess.- The main methods are
on,once,emit,offandremoveAllListeners. - Listeners run synchronously, in registration order.
- Emitting an
errorevent with no listener throws.
Read more