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.
Basic usage: on, emit, removeListener
Section titled “Basic usage: on, emit, removeListener”Needs the Node.js runtime — open in StackBlitz to run.
once — fire exactly one time
Section titled “once — fire exactly one time”once registers a listener that automatically removes itself after the first emission.
Needs the Node.js runtime — open in StackBlitz to run.
Building a custom EventEmitter class
Section titled “Building a custom EventEmitter class”Extend EventEmitter to give your own classes event-driven capabilities.
Needs the Node.js runtime — open in StackBlitz to run.
Listener count and off()
Section titled “Listener count and off()”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.
Needs the Node.js runtime — open in StackBlitz to run.