Hi folks,
while working on my nodes, I also saw the "MaxListenersExceededWarning: Possible EventEmitter memory leak detected..." error. After some research on how to finally solve that, I'd like to share that with you, as I see a lot of questions regarding this warning here in the forum, but did not see an example how to solve it.
The problem with this message is, that it is a warning to prevent the system to loose performance because of too many listeners. If an event is emitted, it is used and processed by all registered listeners. That take processing time. The actual problem here is, if a node continues to add listeners all the time without removing them once they are not need anymore, the system gets slower and slower. We don't want that, of course. So this warning shows the developers (and the users), that there might be a problem. So if we remove the warning, we should be sure, that we don't have this kind of leaking.
This must be done by node developers. Users cannot do that, unless the node has an option to set this value in the editor or in a config node.
There are 2 situation where this error can appear:
- In nodes like mqtt or websocket
They directly use Sockets as part of their code. If you take a look at the code, you see, that they setMaximumListeners in the socket client. - In nodes, that use RED.events.register
Here we use an internal event system, that NR provides in RED.events. The default limit here is set to 11.
In the first situation you can see, that the socket clients are explicitly set, so you should never see the warning here.
More common and interesting for developers, that use eventing in their nodes based on RED.events, the solution is pretty easy. It looks like that:
// in "mynode.js"
module.exports = function (RED) {
/*
set to 0? - be sure you really don't want a warning!
Otherwise set this to the expected limit.
*/
MAX_LISTENERS = 0
RED.events.setMaxListeners(MAX_LISTENERS)
... // continue setting up your nodes
That's it.
As usual, be warned to do that again. By switching the maximum numbers of listeners to 0 (or a very high number), you might run into trouble.
I hope that brings some light into that matter for some of you.