I'm having a problem with the Event Emitter warning in Node.js. I'm trying to connect to MongoDB using Mongoskin. Could you please explain to me why the warning is occurring and how to avoid it?
for (j in self.channel_data) {
( function( channel, index ) {
mongo.collection('revenue_share')
.find({ approved: true,
entity_id: channel.user_channel_id,
date_effective: {$lte: +new Date(self.report_data[channel.report_id].end_date).getTime()}
}, selectables)
.sort({date_effective : -1})
.toArray(function (err, _data) {
if (err || !_data.length) {
return self.fetched_rev_share(channel, null);
}
return self.fetched_rev_share(channel, _data[0]);
});
})(self.channel_data[j], j);
}
Here is the warning being displayed:
(node) warning: possible EventEmitter memory leak detected. 51 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace
at EventEmitter.addListener (events.js:160:15)
at EventEmitter.once (events.js:185:8)
at SkinClass.open (/Users/ninz/Sites/freedom-node-backend/node_modules/mongoskin/lib/utils.js:156:23)
at SkinClass.SkinCollection._open (/Users/ninz/Sites/freedom-node-backend/node_modules/mongoskin/lib/collection.js:49:17)
at SkinClass.open (/Users/ninz/Sites/freedom-node-backend/node_modules/mongoskin/lib/utils.js:162:14)
at SkinClass.SkinCursor._open (/Users/ninz/Sites/freedom-node-backend/node_modules/mongoskin/lib/cursor.js:28:25)
at SkinClass.open (/Users/ninz/Sites/freedom-node-backend/node_modules/mongoskin/lib/utils.js:162:14)
at SkinClass.(anonymous function) [as sort] (/Users/ninz/Sites/freedom-node-backend/node_modules/mongoskin/lib/utils.js:116:14)
at /Users/ninz/Sites/freedom-node-backend/helpers/channel_earnings.js:61:18
at Query.loop_to_channels [as _callback] (/Users/ninz/Sites/freedom-node-backend/helpers/channel_earnings.js:70:7)
The code you are executing (I'm assuming it is because self.channel_data contains 51 keys) causes 51 listeners to be added to an EventEmitter. In order to help prevent memory leaks, EventEmitters throw warnings when you add more than n listeners (10 by default) - which you did in this case.
In order to fix it, you need to set the EventEmitter max listener amount to more than 51 - lets say 75. Here are the docs for that change.
eventemitter.setMaxListeners(75);
I don't have enough experience with the Mongo driver to pinpoint where your eventemitter is, but thats the error.
If you look at node_modules/mongoskin/lib/utils.js, you can see at line 45 that they specifically set the max listeners to 50.
this._emitter.setMaxListeners(50);
What you can do is to globally change this, or just edit it yourself in the js file.
this._emitter.setMaxListeners(0);
0 removes the limit (as far as I know).