Last active
May 30, 2020 11:04
-
-
Save vlasky/2ea30ce9923bd06c2ee100f2924991cc to your computer and use it in GitHub Desktop.
Debugging code to help track down events that cause EventEmitter memory leaks in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Is Node.js reporting warning messages like this?: | |
// | |
// "Warning: Possible EventEmitter memory leak detected. 11 wakeup listeners added. Use emitter.setMaxListeners() to increase limit" | |
// | |
//The following code will intercept calls to addListener() and on() and print the type of event and generate an Error exception | |
//With a stack trace to help you find the cause | |
var EventEmitter = require('events').EventEmitter; | |
const originalAddListener = EventEmitter.prototype.addListener; | |
const addListener = function (type) { | |
originalAddListener.apply(this, arguments); | |
const numListeners = this.listeners(type).length; | |
const max = typeof this._maxListeners === 'number' ? this._maxListeners : 10; | |
if (max !== 0 && numListeners > max) { | |
const error = new Error('Too many listeners of type "' + type + '" added to EventEmitter. Max is ' + max + " and we've added " + numListeners + '.'); | |
console.error(error); | |
throw error; | |
} | |
return this; | |
}; | |
EventEmitter.prototype.addListener = addListener; | |
EventEmitter.prototype.on = addListener; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you! It really helps to debug my app!