0

I've seen that if I press F5 during 15seconds I got a memory leak problem :

(node) warning: possible EventEmitter memory leak detected. 11 change listeners added. Use emitter.setMaxListeners() to increase limit.

Is it possible to avoid that ? I'm using socket.io server side and I set some listeners on connection :

database.on("ready",function(){

    //define all the routes

    io.on("connection", function(socket){
        players.on("change", function change(player) {
           socket.emit("/player", player);
        });

        //other listeners


       //I tried :
       socket.on("disconnect",function(){
            console.log("Disconnected");
            players.removeAllListeners("change");
            //same thing for other listeners
       });
   });
});

Even if I remove all the listeners, I'm still getting this memory leak error which means that the app might have troubles with hundreds of clients. If I press F5 like 1 time per second, the "Disconnected" appears. But if I keep pressing F5 I see "Disconnected" message few seconds after. Like there is a delay. Finally, i'm using express.js

What's wrong ?

Thanks in advance

TLd
  • 602
  • 8
  • 23

2 Answers2

3

The message (node) warning: possible EventEmitter memory leak detected. 11 change listeners added. Use emitter.setMaxListeners() to increase limit. is only a warning that you might run into some memory leak. The hypothesis behind this warning is that registering unbounded event listeners for an event emitter and not removing any event listeners will at the end cause a memory leak. Node.js tries to make a good guess what's a valid count of event listeners (default: 10) and emits a warning in case more than the default event listeners are defined.

Your code seems quite reasonable for me since event listeners database.on("ready") and io.on("connection") are registered only once. The only possibly unbounded event listener registered is players.on("change") because this event listener is registered for every connection established via socket.io but this event listener is removed when the socket is disconnected. So, this seems valid.

The warning message will thus be emitted by node.js whenever you have more than 10 socket.io connections since you register a new event listener for every connection. In this scenario having more than 10 event listeners is perfectly valid. So you should increase the limit for the warning message or allow an infinite count of event listeners using players.setMaxListeners(0).

saintedlama
  • 6,838
  • 1
  • 28
  • 46
0

You also can raise the default limit (10) of event emmiter with the setMaxListeners, for instance:

database.setMaxListeners(100);
Marcos Leonel
  • 78
  • 3
  • 10