Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readNode.js
#Node.js#Events#Memory#Patterns
3D illustration of an emitter horn broadcasting pulses to a ring of listeners with one leaking connection

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

js
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'
js
// 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

MethodRunsRemoves itselfReturnsNotes
on / addListenerEvery emitNothisThe default
onceFirst emit onlyYesthisWrapper; off(fn) still works
prependListenerEvery emit, firstNothisOrdering control
emitNow, synchronously—booleanfalse if no listeners
once(emitter, name)As a promiseYesPromiseRejects on 'error'
on(emitter, name)Async iteratorOn break/throwAsyncIterableBuffers if not consumed
SymptomCauseFix
MaxListenersExceededWarningListener added per request or per itemRemove it, or move ownership
Process exits on 'error'No 'error' listenerAdd one, or handle at the boundary
Emitted event does nothingWrong name, or emitted before subscribingCheck listenerCount
Listener called twiceBoth on and once registered, or a re-subscriberawListeners to inspect
Handler runs after the request endedNo cleanup on completionRemove in finally / close

Practical Edge Cases and Deep Dives

1. The error event that crashes the process

js
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

js
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 skipped

emit 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

js
const onReady = () => start(); emitter.once('ready', onReady); emitter.off('ready', onReady); // works: Node stores the original on .listener

once 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

js
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

bash
node --trace-warnings app.js # shows where the 11th listener was added
js
import { 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

js
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 escaping

With 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

SymptomCauseFix
MaxListenersExceededWarningListener per request on a shared emitterSubscribe once, or remove on close
Error: Unhandled 'error' event'error' emitted with no listenerAdd a listener, or rename the event
unhandledRejection from a listenerAsync listener without captureRejectionsEnable it, or catch inside the listener
Listener fires for a closed resourceNo teardownRemove in 'close' / finally, or bind a signal
Event handler skippedA previous listener threwWrap each listener call, or isolate
emit returns falseNo listener at that momentRegister before emitting, or make emit optional-aware
Memory grows with request countevents.on() queue unboundedConsume faster, or bound the queue
Duplicate side effectsSame handler registered twice (on in a render path)listenerCount, or off before on
Crash during shutdownremoveAllListeners() removed 'error'Remove specific events only

Try matching browser tools

All tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.