Node.js sends warnings when you add too many listeners to an event emitter

Farid Vosoughi
2 min readSep 5, 2022

--

When you use Event in JavaScript you usually also use an EventEmitter. Let's have a quick look at an example snippet from the docs.

const EventEmitter = require('events');class MyEmitter extends EventEmitter {}const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');

The usage is straightforward. Create an emitter, emit events and react to them. Let’s change the code above and add a few more event handlers.

const EventEmitter = require('events');class MyEmitter extends EventEmitter {}const myEmitter = new MyEmitter();
for(let i = 0; i < 11; i++) {
myEmitter.on('event', _ => console.log(i));
}
myEmitter.emit('event');

And execute it.

0
1
2
3
4
5
6
7
8
9
10
(node:54105) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 event listeners added to [MyEmitter]. Use emitter.setMaxListeners() to increase limit

Node.js sends a warning to stderr when you add more than ten listeners for one specific event to an event emitter. Having 30 listeners reacting to 30 different events is fine, though.

This warning helps you to prevent memory leaks. Node.js processes can run for ages and when you have a bug in your code and create a new event listener before cleaning up, or you don’t use existing ones the memory usage of this process will slowly grow and make troubles on your servers at some point.

It has to be pointed out that this is “just” a warning and the Node.js process will still execute the eleven added listeners. It won’t terminate the process, will only appear once per event and it is more about pointing out problems in your source code.

Sometimes you do need more than ten listeners for an event on an event emitter, though. This is the situation, where setMaxListeners comes into play. A function that is also used several times in the Node.js project itself

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
// increase the limit
myEmitter.setMaxListeners(11);

for(let i = 0; i < 11; i++) {
myEmitter.on('event', _ => console.log(i));
}

myEmitter.emit('event');

Using setMaxListeners way you can quickly get rid of warnings regarding the number of listeners and go on with coding. I'd say this warning is a pretty good example of good developer experience.

--

--

Farid Vosoughi
Farid Vosoughi

Written by Farid Vosoughi

Interested in learning new technologies related to software development

No responses yet