EventEmitter: The Event Model at the Core of Node.js
EventEmitter is the common denominator beneath streams, HTTP servers and processes: I show on/once/off/emit, the special behavior of 'error' and how to avoid listener leaks.
That .on('data', …) on a stream, .on('request', …) on an HTTP server and .on('exit', …) on a child process look the same is not a convention that module authors follow voluntarily. The similarity has a technical reason: all of these objects inherit from the same class – the EventEmitter. Once you have mastered this one class, you understand a large part of the standard library.
This article takes the EventEmitter apart: first the idea behind it, then the concrete API, then the two or three places where it hurts in practice. If you want to read up first on why Node is event-driven at all, you will find that in the post on Node.js training around the event loop. This one is about the layer directly above it.
The common denominator beneath everything#
At its core, Node.js is event-driven. An HTTP server does not wait in a loop for the next request; it registers: “When a request comes in, call this function.” A read stream does not say “give me the data” but “let me know when a chunk of data is there.” This pattern – register interest, get notified later – runs through the entire platform.
So that this pattern is not reinvented in every module, there is a shared base class. net.Server, http.Server, the stream classes Readable and Writable, the global process object, the objects from child_process – they are all emitters or inherit from EventEmitter. That explains why .on() feels the same everywhere: it is literally the same method.
classDiagram
class EventEmitter {
+on(event, listener)
+once(event, listener)
+off(event, listener)
+emit(event, ...args)
}
EventEmitter <|-- HttpServer
EventEmitter <|-- Readable
EventEmitter <|-- Writable
EventEmitter <|-- Process
EventEmitter <|-- MyEmitter
class HttpServer["http.Server"]
class Readable["stream.Readable"]
class Writable["stream.Writable"]
class Process["process"]
class MyEmitter["custom class"]The class itself lives in the built-in module events. You get it the classic way via require('events') or – possible since Node 16 – with the prefix require('node:events'). Both forms return the same class; the prefix just makes it unmistakably clear that a built-in module is meant and not a package from node_modules.
The four methods everything revolves around#
The emitter’s API is surprisingly small. Four methods are enough for everyday work. Three of them – on, once and off – return the emitter itself and can therefore be chained; emit is the exception and returns a boolean instead, as we will see in a moment.
const { EventEmitter } = require('node:events');
const emitter = new EventEmitter();
function onTask(job) {
console.log('received task', job.id);
}
emitter.on('task', onTask); // register a listener
emitter.emit('task', { id: 1 }); // trigger it synchronously
emitter.off('task', onTask); // remove it again
on(eventName, listener) appends a listener to the end of the list for this event. emit(eventName, ...args) calls all registered listeners and passes the additional arguments through. off(eventName, listener) – alias removeListener – takes a listener out again. And once(eventName, listener) registers a listener that disappears automatically after it fires the first time.
Two properties of emit are crucial for understanding, and both are often overlooked:
emitcalls the listeners synchronously. There is nothing asynchronous here, no detour through the event loop, no delay. Whenemitreturns, all listeners have run.- The listeners run in the order they were registered. Whoever called
on()first has their function run first.
sequenceDiagram
participant C as Caller
participant E as EventEmitter
participant L1 as Listener 1
participant L2 as Listener 2
C->>E: emit('task', data)
E->>L1: listener(data)
L1-->>E: done
E->>L2: listener(data)
L2-->>E: done
E-->>C: return trueThe return value of emit is a boolean: true if there was at least one listener for this event, otherwise false. What the listeners themselves return does not interest the emitter – return values from listeners are simply ignored. If you want to report something to the outside from within a listener, you have to do it another way, such as another event or shared state.
on, once and off working together#
The difference between on and once sounds harmless but has consequences. A listener registered with once is removed from the list before its own call and then executed. So it is guaranteed to fire exactly once, no matter how often the event is triggered afterward.
const { EventEmitter } = require('node:events');
const queue = new EventEmitter();
let handled = 0;
queue.on('task', () => { handled += 1; });
let drained = 0;
queue.once('drain', () => { drained += 1; });
queue.emit('task'); // handled = 1
queue.emit('task'); // handled = 2
queue.emit('drain'); // drained = 1
queue.emit('drain'); // drained stays 1 - the listener is gone
Removal deserves a close look. off removes at most one instance of a listener. If you accidentally registered the same function twice with on, you also need two off calls to get rid of it completely. And you can only remove what you can name – an anonymous arrow function that you pass directly to on is out of your hands afterward. That is why I always register listeners that I want to unregister later as a named function or as a variable.
Here are the semantics of the four at a glance:
on– the listener stays registered and runs again on everyemit.once– the listener runs exactly once and removes itself beforehand.off– removes one instance of a named listener; you cannot get rid of anonymous functions this way.emit– calls all listeners synchronously in registration order and returnstrue/false.
Besides these four, there are some useful side methods: prependListener adds a listener to the beginning instead of the end, removeAllListeners cleans up completely, listeners(eventName) returns a copy of the current listener list and eventNames() tells you which events anyone is registered for at all. You rarely need them, but when you do, they are worth their weight in gold – for example when debugging the question “who is actually listening here?”
The error event is a special case#
This quirk once cost a running process in a project: the 'error' event behaves differently from all others. For an ordinary event without listeners, nothing happens – emit returns false, and that is that. Not so for the 'error' event.
If an emitter calls emit('error', ...) and no listener is registered for 'error', the error is thrown. And because it is thrown inside the emitter machinery and nobody catches it, it can take down the whole process. This turns “a stream complained” into a complete crash of the Node process.
const { EventEmitter } = require('node:events');
const source = new EventEmitter();
// Without this listener the next line would crash the process:
source.on('error', (err) => {
console.error('handled:', err.message);
});
source.emit('error', new Error('boom')); // handled cleanly
By the way, this is not harassment but a deliberate decision by the Node team. An error that nobody handles should be loud and not silently swallowed. This leads to a simple rule: for every emitter that can report errors – and that is practically all streams, all network objects, all child processes – I register an 'error' listener before the actual work starts. It is the safety net without which the whole application breaks on a single unhandled message.
There are two more special events used internally: 'newListener' fires before a new listener is added, and 'removeListener' fires after one has been removed. Both are meant more for tools and diagnostics than for everyday use, but it is good to know they exist if you ever want to watch who registers or unregisters when.
Too many listeners: the leak warning#
Node keeps track, for every emitter, of how many listeners are registered per event. If this number exceeds a threshold – 10 by default – Node prints a warning to stderr: the MaxListenersExceededWarning.
This warning is not an error and stops nothing. It is a heuristic against a very common class of bugs: the listener leak. The typical case is that somewhere, per request, per loop iteration or per retry, an on() is called, but the matching off() is missing. The listeners pile up, memory grows, and at some point Node speaks up.
const { EventEmitter } = require('node:events');
const bus = new EventEmitter();
// Optional: make the warning itself visible
process.on('warning', (warning) => {
console.log(warning.name, '- count:', warning.count);
});
// Anti-pattern: a new, never-removed listener on every iteration
for (let i = 0; i < 12; i += 1) {
bus.on('data', (chunk) => processChunk(chunk));
}
// From the 11th listener on, the MaxListenersExceededWarning appears.
What matters is this: the warning is the symptom, not the cause. The cause is the registration that is never removed. If you silence the warning with emitter.setMaxListeners(Infinity), you have only taped over the warning light – the leak keeps running, memory keeps growing. The right fix is to unregister listeners when you no longer need them, or to register them as once right away if they should only fire once anyway.
function onData(chunk) {
processChunk(chunk);
}
bus.on('data', onData);
// ... later, when done:
bus.off('data', onData); // cleanly removed, no pile-up
That does not mean the threshold of 10 is set in stone. There are legitimate cases where an emitter deliberately has more listeners. Then you adjust it intentionally: emitter.setMaxListeners(n) raises the limit for a single emitter, events.defaultMaxListeners = n moves the global default. The value 0 or Infinity turns the warning off entirely. The only important thing is that this decision is a conscious one and not a reflex to get rid of the message in the log.
Building your own class#
The EventEmitter is not just something the standard library inherits from – you can just as well use it as a base yourself. Whenever a component of yours should inform its surroundings about things without knowing the receivers in advance, an emitter is the obvious choice.
The pattern is class MyThing extends EventEmitter with a super() call in the constructor. Here is a small task queue that reports when a task is added, when it is done and when something goes wrong:
const { EventEmitter } = require('node:events');
class TaskQueue extends EventEmitter {
constructor() {
super();
this.pending = [];
}
add(job) {
this.pending.push(job);
this.emit('task', job);
}
run() {
while (this.pending.length > 0) {
const job = this.pending.shift();
try {
job.handler();
this.emit('done', job);
} catch (cause) {
// Only emit 'error' when a listener exists -
// otherwise it crashes the process:
if (this.listenerCount('error') > 0) {
this.emit('error', cause);
} else {
throw cause;
}
}
}
this.emit('drain');
}
}
const queue = new TaskQueue();
queue.on('task', (job) => console.log('queued', job.id));
queue.on('done', (job) => console.log('done', job.id));
queue.once('drain', () => console.log('all work finished'));
queue.on('error', (err) => console.error('failed:', err.message));
queue.add({ id: 1, handler: () => {} });
queue.add({ id: 2, handler: () => { throw new Error('bad job'); } });
queue.run();
This example shows several things working together. The queue does not know its listeners – it calls emit, and whoever wants to listens. once('drain', ...) makes sure the completion message arrives exactly once. And in the error case, I check with listenerCount('error') whether anyone is listening at all before I call emit('error', ...). That way I avoid the crash from an unhandled 'error' event and instead let the error continue as an ordinary exception if nobody catches it.
A small but recurring stumbling block with your own classes concerns this. In a classic function listener, this points to the emitter that triggered the event – handy if you want to access the emitter from inside. In an arrow function, that does not apply; there, this keeps its meaning from the surrounding context. Both are legitimate; you just need to be aware of which variant you choose.
Synchronous means synchronous#
Finally, one clarification that prevents bugs in everyday work. Because Node is so strongly associated with asynchrony, many people intuitively assume that emit calls the listeners at some later point. It does not. The call is synchronous, and the listeners block the calling code until they are done.
Most of the time, that is exactly right, because it makes the flow predictable. But if, inside a listener, you deliberately want to move something out of the current flow – so that long work does not hold up the emit caller – you have to do that explicitly, for example with setImmediate or process.nextTick. The emitter itself reschedules nothing; it just calls, in order, whatever is registered.
Conclusion#
The EventEmitter is a small class with a big reach. Four methods – on, once, off, emit – carry everyday work, and because a large part of the standard library inherits from exactly this class, the understanding carries over directly to streams, servers and processes. Two things you should never lose sight of: without a listener, the 'error' event crashes the process, so an 'error' listener belongs wherever errors can be reported. And the MaxListenersExceededWarning is an honest warning sign of a leak, not an annoying notice you configure away. With these two reflexes, you write event-driven Node code that keeps running stably even when things get uncomfortable.
Further reading#
- Node.js docs: Events API
- Node.js guide: The Node.js Event emitter
- Node.js docs: Stream API (inherits from
EventEmitter) - My own post: Node.js training around the event loop
Revised and translated from German with the help of AI.