Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs MaxListenersExceededWarning

I have an error and I don't know how to solve it. It happens only some times.

Error message:

(node:9140) MaxListenersExceededWarning: Possible EventEmitter memory leak detec
ted. 11 error listeners added. Use emitter.setMaxListeners() to increase limit
like image 979
Stepan Rafael Avatar asked Apr 20 '18 16:04

Stepan Rafael


1 Answers

This error often occurs when you are using EventEmitters directly or indirectly in your code and you are creating too many in too short a period for them to be resolved -- Node detects this as a memory leak and throws an error once the Max Listener count has been exceeded.

For example, it's often common in unit tests to setup and tear-down pre-conditions before and after each test. Test runners, like Mocha, will often run tests in parallel. If you have dozens of tests then you can quickly run the Event Listener count over the maximum if your setup performs operations that emit events (e.g. Connecting to a Database).

Without your specific code, it would be difficult to pinpoint the cause. I recommend you review your code for any Event Emitters that you may have used, either directly or in modules that you are including, and look for any instances where you may be inadvertently creating too many of them in parallel (e.g. through Promises or async). The key is to look for places in your code where you have a lot of "parallel execution" such as loops with Promises. For context, parallel execution is in quotes here because of the pseudo-parallel nature of the NodeJs Event Loop

By default Node usually only allows a maximum of 10 listeners. You can override the number of emitters Node will allow using:

setMaxListeners(n);

However, you should be aware that this is just a warning and it is intended to assist the developer by warning them when they have code that may be causing a memory leak.

like image 120
JayReardon Avatar answered Nov 20 '22 18:11

JayReardon