Skip to content

EventEmitter

The backbone of Node’s event-driven model

Section titled “The backbone of Node’s event-driven model”

EventEmitter (from node:events) is the class that powers virtually every I/O object in Node.js. The HTTP server, TCP sockets, file streams, child processes, and many third-party libraries all extend EventEmitter. Understanding it means understanding how Node communicates between components.

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

once registers a listener that automatically removes itself after the first emission.

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

Extend EventEmitter to give your own classes event-driven capabilities.

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

off is an alias for removeListener added in Node 10. listenerCount lets you inspect how many listeners are registered for an event — useful for detecting potential memory leaks.

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

What is the key difference between emitter.on() and emitter.once()?
When does an EventEmitter listener run relative to emitter.emit()?
Which Node.js built-in classes extend EventEmitter?