Memory & listeners
Leaks
1. The Default Limit
By default, Node.js allows a maximum of 10 listeners for a single event on one emitter. This is a safety feature designed to help you find memory leaks.
Why? If you accidentally add a listener inside a loop or a frequently called function, you’ll quickly exceed this limit.
The Warning: When you hit 11 listeners, Node.js will print a
MaxListenersExceededWarningto the console.
myEmitter.setMaxListeners(20);2. What is a Listener Leak?
A memory leak occurs when a listener is added to an emitter but is never removed. Since the emitter holds a reference to the listener function, the Garbage Collector cannot remove that function (or any variables it references) from memory.
Common Cause: Closures
If your listener uses variables from its parent scope, those variables stay in memory as long as the listener is attached.
function setup() {
const largeData = new Array(1000000).fill('data'); // Heavy memory usage
myEmitter.on('update', () => {
console.log(largeData.length); // largeData is now "trapped" in memory
});
}
// Even after setup() finishes, largeData cannot be cleared because the listener is still active.3. Cleaning Up (Managing Memory)
To prevent leaks, you must remove listeners when they are no longer needed.
Manual Removal
To remove a specific listener, you must have a reference to the function. Anonymous functions cannot be easily removed.
const onMessage = (msg) => console.log(msg);
// Add
myEmitter.on('message', onMessage);
// Remove later (e.g., when a component unmounts or a user disconnects)
myEmitter.removeListener('message', onMessage);
// OR
myEmitter.off('message', onMessage);Automatic Cleanup with .once()
If you only care about the event happening one time, use .once(). Node.js will automatically call .removeListener() for you after the event fires.
4. Inspecting Listeners
If you suspect a leak, you can inspect the current state of your emitter:
myEmitter.listenerCount('eventName'): Returns the number of listeners for a specific event.
myEmitter.rawListeners('eventName'): Returns an array of the actual listener functions.5. AbortController (Modern Cleanup)
In modern Node.js, you can use an AbortController to remove multiple listeners at once using a signal. This is very useful for cleaning up complex event chains.
const ac = new AbortController();
const { signal } = ac;
myEmitter.on('data', () => { ... }, { signal });
// Later, stop all listeners associated with this signal
ac.abort();.