Node.js EventEmitter: once, error Events, and Listener Memory Leaks
emit is synchronous, so a throwing listener aborts the rest. An error event with no listener crashes the process, and a listener per request is the classic leak.

Quick Summary
EventEmitter is Node's observer pattern: an object holds a list of functions per event name, on adds one, emit calls them synchronously in registration order. Streams, servers, sockets, and most core modules extend it.
The 'error' event is special. Emitting it with no listener throws the error out of emit(), which typically ends the process; this is deliberate, so that a failure cannot be silently dropped. Any emitter you own should either handle 'error' or document that it never emits one.
Memory leaks in Node are usually listener leaks. MaxListenersExceededWarning appears at eleven listeners on one event, and the usual cause is registering a handler per request, per socket, or per render on an emitter that outlives them. setMaxListeners(0) disables the warning, not the leak.
Basic Syntax and Core Signatures
import { EventEmitter, once, on, getEventListeners } from 'node:events';
class Queue extends EventEmitter {
add(job) {
this.emit('job', job); // synchronous; returns true if listeners existed
}
}
const q = new Queue();
// Subscribe
q.on('job', handler); // returns the emitter
q.once('ready', () => console.log('once only'));
q.prependListener('job', () => console.log('first'));
q.off('job', handler); // alias: removeListener
q.removeAllListeners('job');
// Introspection
q.listenerCount('job');
q.eventNames();
q.listeners('job'); // unwrapped (original) functions
q.rawListeners('job'); // includes once() wrappers
q.setMaxListeners(20);
// Await one event
const [payload] = await once(q, 'job');
const [val, rej] = await Promise.race([
once(q, 'value'),
once(q, 'error'), // note: once() rejects on 'error' automatically
]);
// Async iteration over events
for await (const [job] of on(q, 'job', { signal: ac.signal })) {
await process(job);
}
// Async listeners with rejection capture
const e = new EventEmitter({ captureRejections: true });
e.on('work', async () => { throw new Error('failed'); }); // routed to 'error'// The classic leak: a global emitter, one listener per request
app.use((req, res, next) => {
bus.on('config:reload', () => res.locals.config = loadConfig()); // never removed
next();
});Key Comparison Table
| Method | Runs | Removes itself | Returns | Notes |
|---|---|---|---|---|
on / addListener | Every emit | No | this | The default |
once | First emit only | Yes | this | Wrapper; off(fn) still works |
prependListener | Every emit, first | No | this | Ordering control |
emit | Now, synchronously | — | boolean | false if no listeners |
once(emitter, name) | As a promise | Yes | Promise | Rejects on 'error' |
on(emitter, name) | Async iterator | On break/throw | AsyncIterable | Buffers if not consumed |
| Symptom | Cause | Fix |
|---|---|---|
MaxListenersExceededWarning | Listener added per request or per item | Remove it, or move ownership |
Process exits on 'error' | No 'error' listener | Add one, or handle at the boundary |
| Emitted event does nothing | Wrong name, or emitted before subscribing | Check listenerCount |
| Listener called twice | Both on and once registered, or a re-subscribe | rawListeners to inspect |
| Handler runs after the request ended | No cleanup on completion | Remove in finally / close |
Practical Edge Cases and Deep Dives
1. The error event that crashes the process
const bus = new EventEmitter();
bus.emit('error', new Error('boom'));
// Error: boom (thrown, unhandled, process exits)An 'error' event with no listener is rethrown by emit(). That is a feature for streams and sockets — a failed connection cannot be ignored by omission — and a trap for domain emitters where 'error' is just another message. If your emitter uses the name for a non-fatal case, rename the event; removeAllListeners() with no argument also removes the 'error' handler, which is why a cleanup routine can turn a handled failure into a crash.
2. Synchronous emit and exceptions
bus.on('job', () => { throw new Error('listener failed'); });
bus.on('job', () => console.log('never runs'));
bus.emit('job', 1); // the throw propagates out of emit(); the second listener is skippedemit is a plain loop over listeners, so a throwing listener aborts the remaining ones and surfaces in whoever called emit. There is no isolation and no async queueing. Emitters that fan out to untrusted listeners should wrap each call in try/catch, and async listeners need captureRejections: true — without it a rejected promise inside an async listener becomes an unhandled rejection, not an error event.
3. Removing a once listener correctly
const onReady = () => start();
emitter.once('ready', onReady);
emitter.off('ready', onReady); // works: Node stores the original on .listeneronce wraps the function, but the wrapper exposes .listener and removeListener matches on it, so the obvious code works. What does not work is creating the wrapper elsewhere (once(fn) from node:events returns a wrapper whose .listener is fn) and then calling off with a new closure — identity is by reference. For signal-driven cleanup, events.once(emitter, name, { signal }) removes the listener when the signal aborts, which is the cleanest way to avoid leaks in request-scoped subscriptions.
4. Async iteration and backpressure
for await (const [batch] of on(bus, 'batch', { highWaterMark: 4 })) {
await slow(batch);
}events.on() returns an async iterator with its own queue. Events keep arriving while the loop body is awaiting, and once the queue exceeds highWaterMark (default 64) the emitter warns and buffers without limit — so a slow consumer of a fast producer becomes a memory leak with a warning attached. If the producer can outrun the consumer, the consumer needs a bounded queue of its own, or the producer needs to await a result rather than fire and forget.
5. Listener leaks: finding them, not silencing them
node --trace-warnings app.js # shows where the 11th listener was addedimport { getEventListeners } from 'node:events';
console.log(getEventListeners(process, 'warning').length);
console.log(process.listenerCount('SIGTERM'));The warning names the emitter and the event, and --trace-warnings shows the stack that added the eleventh listener — usually a useEffect, a request handler, or a for loop over sockets. Raising setMaxListeners is legitimate only when you know the count is bounded by design (one listener per active connection, capped elsewhere). emitter.on on a module-level singleton from inside a request path is the pattern to search for first.
6. captureRejections and where the error lands
const e = new EventEmitter({ captureRejections: true });
e.on('job', async (id) => {
if (bad(id)) throw new Error(`bad job ${id}`);
});
e.emit('job', 1); // rejections are routed to 'error' instead of escapingWith captureRejections, a rejected promise from an async listener is emitted as 'error', or handed to a Symbol.for('nodejs.rejection') method if the emitter defines one. Without it, the rejection is unhandled and Node terminates on unhandledRejection under strict settings. This is also why an async listener that throws in an emitter without the option can take down a process that looks fully guarded by a try/catch around emit() — the catch sees the synchronous part only.
Common Node.js Runtime Mistakes
| Symptom | Cause | Fix |
|---|---|---|
MaxListenersExceededWarning | Listener per request on a shared emitter | Subscribe once, or remove on close |
Error: Unhandled 'error' event | 'error' emitted with no listener | Add a listener, or rename the event |
unhandledRejection from a listener | Async listener without captureRejections | Enable it, or catch inside the listener |
| Listener fires for a closed resource | No teardown | Remove in 'close' / finally, or bind a signal |
| Event handler skipped | A previous listener threw | Wrap each listener call, or isolate |
emit returns false | No listener at that moment | Register before emitting, or make emit optional-aware |
| Memory grows with request count | events.on() queue unbounded | Consume faster, or bound the queue |
| Duplicate side effects | Same handler registered twice (on in a render path) | listenerCount, or off before on |
| Crash during shutdown | removeAllListeners() removed 'error' | Remove specific events only |
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesNode.js fs/promises: Read, Write, Watch, and Atomic File Operations
writeFile truncates before writing, so a crash leaves half a file. The atomic pattern is temp file, fsync, rename; readFile loads everything, so large files need streams.
Node.js Streams: Readable, Writable, Transform, and pipeline
pipe() forwards data but not errors; pipeline() destroys the chain and rejects. Backpressure is the false return from write(), and _flush that never calls back hangs forever.
Node.js crypto: Hashing, HMAC, AES-GCM, and Random Bytes
Hashing, HMAC, AES-256-GCM and randomness solve different problems. Never reuse a GCM nonce, never hash a password with sha256, and compare secrets with timingSafeEqual.
Node.js Buffer and TypedArray: Encodings and Binary Manipulation
A Buffer is a view over an ArrayBuffer, so byteLength is not string length and toString can silently corrupt split UTF-8. allocUnsafe and pooled buffers carry old data.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.