QA
Intermediate LevelNode JS

Why does EventEmitter throw "Possible EventEmitter memory leak detected. 11 listeners added" and how do you fix it?

❓ Interview Prompt: Node warns when >10 listeners attach to a single event to catch accidental listener loops in render passes. Increase limit legitimately via emitter.setMaxListeners(20) or ensure listeners are removed with .off().

Node.js 'EventEmitter' defaults to a maximum of 10 listeners per event type as a diagnostic safety check to alert developers to potential memory leaks!

Resolving Warnings:

1
Ensure unused event listeners are removed via 'emitter.off(event, listener)' or 'emitter.removeListener()'.
2
Legitimate high-listener subscriptions can increase the cap via 'emitter.setMaxListeners(50)'.

Code Implementation Example

javascript
import { EventEmitter } from 'node:events';

const emitter = new EventEmitter();

// Legotimately increase max listener limit for high-concurrency pub-sub
emitter.setMaxListeners(50);

// Clean up listener when no longer needed!
function handleEvent() { /* ... */ }
emitter.on('data', handleEvent);
// Later:
emitter.off('data', handleEvent);
💡Increasing listener limits and cleaning up event listeners.
🎯 Interview Key Takeaway

Remove unused event listeners with emitter.off() to prevent memory leaks and warning logs.

#EventEmitter#setMaxListeners#Memory Leaks#Intermediate
Back to all Node JS Questions→

More Node JS Interview Questions

Beginner LevelNode JS

How does the Node.js Event Loop work? Explain the 6 execution phases (Timers, Pending, Poll, Check, Close).

Beginner LevelNode JS

What does 'Single-Threaded, Event-Driven, Non-Blocking I/O' mean in Node.js?

Beginner LevelNode JS

What is the difference between process.nextTick() and setImmediate()?