Firebase Function Deployment Possible EventEmitter memory leak [duplicate] - node.js

I am getting following warning:
(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace:
at EventEmitter.<anonymous> (events.js:139:15)
at EventEmitter.<anonymous> (node.js:385:29)
at Server.<anonymous> (server.js:20:17)
at Server.emit (events.js:70:17)
at HTTPParser.onIncoming (http.js:1514:12)
at HTTPParser.onHeadersComplete (http.js:102:31)
at Socket.ondata (http.js:1410:22)
at TCP.onread (net.js:354:27)
I wrote code like this in server.js:
http.createServer(
function (req, res) { ... }).listen(3013);
How to fix this ?

I'd like to point out here that that warning is there for a reason and there's a good chance the right fix is not increasing the limit but figuring out why you're adding so many listeners to the same event. Only increase the limit if you know why so many listeners are being added and are confident it's what you really want.
I found this page because I got this warning and in my case there was a bug in some code I was using that was turning the global object into an EventEmitter! I'd certainly advise against increasing the limit globally because you don't want these things to go unnoticed.

This is explained in the node eventEmitter documentation
What version of Node is this? What other code do you have? That isn't normal behavior.
In short, its: process.setMaxListeners(0);
Also see: node.js - request - How to “emitter.setMaxListeners()”?

The accepted answer provides the semantics on how to increase the limit, but as #voltrevo pointed out that warning is there for a reason and your code probably has a bug.
Consider the following buggy code:
//Assume Logger is a module that emits errors
var Logger = require('./Logger.js');
for (var i = 0; i < 11; i++) {
//BUG: This will cause the warning
//As the event listener is added in a loop
Logger.on('error', function (err) {
console.log('error writing log: ' + err)
});
Logger.writeLog('Hello');
}
Now observe the correct way of adding the listener:
//Good: event listener is not in a loop
Logger.on('error', function (err) {
console.log('error writing log: ' + err)
});
for (var i = 0; i < 11; i++) {
Logger.writeLog('Hello');
}
Search for similar issues in your code before changing the maxListeners (which is explained in other answers)

By default, a maximum of 10 listeners can be registered for any single event.
If it's your code, you can specify maxListeners via:
const emitter = new EventEmitter()
emitter.setMaxListeners(100)
// or 0 to turn off the limit
emitter.setMaxListeners(0)
But if it's not your code you can use the trick to increase the default limit globally:
require('events').EventEmitter.prototype._maxListeners = 100;
Of course you can turn off the limits but be careful:
// turn off limits by default (BE CAREFUL)
require('events').EventEmitter.prototype._maxListeners = 0;
BTW. The code should be at the very beginning of the app.
ADD: Since node 0.11 this code also works to change the default limit:
require('events').EventEmitter.defaultMaxListeners = 0

Replace .on() with once(). Using once() removes event listeners when the event is handled by the same function.
If this doesn't fix it, then reinstall restler with this in your package.json
"restler": "git://github.com/danwrong/restler.git#9d455ff14c57ddbe263dbbcd0289d76413bfe07d"
This has to do with restler 0.10 misbehaving with node. you can see the issue closed on git here: https://github.com/danwrong/restler/issues/112
However, npm has yet to update this, so that is why you have to refer to the git head.

Node Version : v11.10.1
Warning message from stack trace :
process.on('warning', e => console.warn(e.stack));
(node:17905) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 wakeup listeners added. Use emitter.setMaxListeners() to increase limit
MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 wakeup listeners added. Use emitter.setMaxListeners() to increase limit
at _addListener (events.js:255:17)
at Connection.addListener (events.js:271:10)
at Connection.Readable.on (_stream_readable.js:826:35)
at Connection.once (events.js:300:8)
at Connection._send (/var/www/html/fleet-node-api/node_modules/http2/lib/protocol/connection.js:355:10)
at processImmediate (timers.js:637:19)
at process.topLevelDomainCallback (domain.js:126:23)
After searching for github issues, documentation and creating similar event emitter memory leaks, this issue was observed due to node-apn module used for iOS push notification.
This resolved it :
You should only create one Provider per-process for each
certificate/key pair you have. You do not need to create a new
Provider for each notification. If you are only sending notifications
to one app then there is no need for more than one Provider.
If you are constantly creating Provider instances in your app, make
sure to call Provider.shutdown() when you are done with each provider
to release its resources and memory.
I was creating provider object each time the notification was sent and expected the gc to clear it.

I am getting this warning too when install aglio on my mac osx.
I use cmd fix it.
sudo npm install -g npm#next
https://github.com/npm/npm/issues/13806

In my case, it was child.stderr.pipe(process.stderr) which was being called when I was initiating 10 (or so) instances of the child. So anything, that leads to attach an event handler to the same EventEmitter Object in a LOOP, causes nodejs to throw this error.

Sometimes these warnings occur when it isn't something we've done, but something we've forgotten to do!
I encountered this warning when I installed the dotenv package with npm, but was interrupted before I got around to adding the require('dotenv').load() statement at the beginning of my app. When I returned to the project, I started getting the "Possible EventEmitter memory leak detected" warnings.
I assumed the problem was from something I had done, not something I had not done!
Once I discovered my oversight and added the require statement, the memory leak warning cleared.

I prefer to hunt down and fix problems instead of suppressing logs whenever possible. After a couple days of observing this issue in my app, I realized I was setting listeners on the req.socket in an Express middleware to catch socket io errors that kept popping up. At some point, I learned that that was not necessary, but I kept the listeners around anyway. I just removed them and the error you are experiencing went away. I verified it was the cause by running requests to my server with and without the following middleware:
socketEventsHandler(req, res, next) {
req.socket.on("error", function(err) {
console.error('------REQ ERROR')
console.error(err.stack)
});
res.socket.on("error", function(err) {
console.error('------RES ERROR')
console.error(err.stack)
});
next();
}
Removing that middleware stopped the warning you are seeing. I would look around your code and try to find anywhere you may be setting up listeners that you don't need.

Thanks to RLaaa for giving me an idea how to solve the real problem/root cause of the warning. Well in my case it was MySQL buggy code.
Providing you wrote a Promise with code inside like this:
pool.getConnection((err, conn) => {
if(err) reject(err)
const q = 'SELECT * from `a_table`'
conn.query(q, [], (err, rows) => {
conn.release()
if(err) reject(err)
// do something
})
conn.on('error', (err) => {
reject(err)
})
})
Notice there is a conn.on('error') listener in the code. That code literally adding listener over and over again depends on how many times you call the query.
Meanwhile if(err) reject(err) does the same thing.
So I removed the conn.on('error') listener and voila... solved!
Hope this helps you.

As pointed out by others, increasing the limit is not the best answer. I was facing the same issue, but in my code I was nowhere using any event listener. When I closely looked into the code, I was creating a lot of promises at times. Each promise had some code of scraping the provided URL (using some third-party library). If you are doing something like that, then it may be the cause.
Refer this thread on how to prevent that: What is the best way to limit concurrency when using ES6's Promise.all()?

i was having the same problem. and the problem was caused because i was listening to port 8080, on 2 listeners.
setMaxListeners() works fine, but i would not recommend it.
the correct way is to, check your code for extra listeners, remove the listener or change the port number on which you are listening, this fixed my problem.

I was having this till today when I start grunt watch. Finally solved by
watch: {
options: {
maxListeners: 99,
livereload: true
},
}
The annoying message is gone.

You need to clear all listeners before creating new ones using:
Client / Server
socket.removeAllListeners();
Assuming socket is your client socket / or created server socket.
You can also subscribe from specific event listeners like for example removing the connect listener like this:
this.socket.removeAllListeners("connect");

I was facing the same issue, but i have successfully handled with async await.
Please check if it helps.
let dataLength = 25;
Before:
for (let i = 0; i < dataLength; i++) {
sftp.get(remotePath, fs.createWriteStream(xyzProject/${data[i].name}));
}
After:
for (let i = 0; i < dataLength; i++) {
await sftp.get(remotePath, fs.createWriteStream(xyzProject/${data[i].name}));
}

In my case it was due to not closing the Sequelize connections to database while creating them inside of the async function called with setInterval.

You said you are using process.on('uncaughtException', callback);
Where are you executing this statement? Is it within the callback passed to http.createServer?If yes, different copy of the same callback will get attached to the uncaughtException event upon each new request, because the function (req, res) { ... } gets executed everytime a new request comes in and so will the statement process.on('uncaughtException', callback);Note that the process object is global to all your requests and adding listeners to its event everytime a new request comes in will not make any sense. You might not want such kind of behaviour. In case you want to attach a new listener for each new request, you should remove all previous listeners attached to the event as they no longer would be required using: process.removeAllListeners('uncaughtException');

Our team's fix for this was removing a registry path from our .npmrc. We had two path aliases in the rc file, and one was pointing to an Artifactory instance that had been deprecated.
The error had nothing to do with our App's actual code but everything to do with our development environment.

Adding EventEmitter.defaultMaxListeners = <MaxNumberOfClients> to node_modules\loopback-datasource-juggler\lib\datasource.js fixed may problem :)

Put this in the first line of your server.js (or whatever contains your main Node.js app):
require('events').EventEmitter.prototype._maxListeners = 0;
and the error goes away :)

Related

Handling errors at a global level

I am trying to understand how to build my error handling system for my api.
Let's say I have a the following line in a controller method :
var age = json.info.age;
with
json = {"id":1, "name":"John", info": {"age":27, "sex":"m"}}
Let's say that the object doesn't contain an info field, I'll get the following error TypeError: Cannot read property 'info' of undefined and my server will crash.
Is there a way to make a higher level abstraction and catch all the potential errors that I could have? Or should I have a try/catch system for each of the methods of my controllers?
BEWARE OF THE CODE BELOW, IT WILL BITE YOU WHENEVER IT CAN!
Don't use the code snippet below if you do not understand its
implications, please read the whole answer.
You can use the node way for uncaught errors. Add this in your config/bootstrap.js
Updated the snippet below to add what was said in the comments, also added a warning about using a global to respond to the user.
process.on('uncaughtException', function (err) {
// Handle your errors here
// global.__current__ is added via middleware
// Be aware that this is a bad practice,
// global.__current__ being a global, can change
// without advice, so you might end responding with
// serverError() to a different request than the one
// that originated the error if this one happened async
global.__current__.res.serverError();
})
Now, can doesn't mean should. It really depends on your needs, but do not try to catch BUGS in your code, try to catch at a controller level the issues that might not happen every time but are somehow expected, like a third-party service that responded with empty data, you should handle that in your controller. The uncaughtException is mainly for logging purposes, its better to let your app crash if there is a bug. Or you can do something more complicated (that might be better IMHO), which is to stop receiving requests, respond to the error 500 (or a custom one) to user that requested the faulty endpoint, and try to complete the other requests that do not relate to that controller, then log and shutdown the server. You will need several instances of sails running to avoid zero downtime, but that is material for another question. What you asked is how to get uncaught exceptions at a higher lvl than the controllers.
I suggest you read the node guide for error handling
Also read about domains, even thought they are deprecated you can use them, but you would have to deal with them per controller action, since sails does not provide any help with that.
I hope it helps.
You can check this way if you want to:
if (object != null && object.response != null && object.response.docs != null){
//Do your stuff here with your document
}
I don't really get what is your "object" variable in the first place, so i don't know if you can check it at a different level, is it a sails parameter to your controller ?
So that's how I did it, thanks to Zagen's answer.
module.exports.bootstrap = function(cb) {
process.on('uncaughtException', function (err) {
//Handle your errors here
logger.fatal(err);
global.__current__.res.serverError();
})
cb();
};
I send a generic error 500 to the user if any uncaught exception is thrown, and I log the error to the fatal level. On that way, my server is still accessible 24/7 and I can monitor the logs at another level and trigger an alarm on a fatal error. I can then fix the exception that was thrown.

Catch all `error` events from any EventEmitter in node

Via the Node.js documentation, an unhandled EventEmitter will crash a running process:
When an EventEmitter instance experiences an error, the typical action is to emit an 'error' event. Error events are treated as a special case in node. If there is no listener for it, then the default action is to print a stack trace and exit the program.
I would very much like for the process to not crash when this happens.[1] Ideally, I could catch every instance of an EventEmitter error like this:
emitter.on('error', function(err) { console.log(err); })
However our application is large, a simple search of the node_modules folder reveals that there are lots of EventEmitters, and tracking them down would be cumbersome.
Is there a global hook I can use to catch all instances of an EventEmitter failure?
I tried process.on('uncaughtException') but this doesn't catch EventEmitter errors. I also tried process.on('error') which catches errors emitted by the process, but does not catch errors emitted by other EventEmitters.
Other places say you should use domains, however, it sounds like you need to wrap specific function calls in it, at which point you might as well find and wrap every EventEmitter with .on('error'). My colleague also says domains are, if not deprecated, not going to be used going forward.
[1] I understand the logic behind the "processes should crash" argument. Partly I would like to keep processes alive because a) our server takes a long time to restart, and b) processes keep crashing with literally zero stack trace; I figure keeping the process alive will help with logging and tracking down errors.
process.on('uncaughtException', ...) does catch EventEmittor errors. Try this:
'use strict';
setInterval(function () {}, Number.MAX_VALUE); // keep process alive
var myEmitter = new (require('events').EventEmitter)();
// add this handler before emitting any events
process.on('uncaughtException', function (err) {
console.log('UNCAUGHT EXCEPTION - keeping process alive:', err); // err.message is "foobar"
});
myEmitter.emit('error', new Error('foobar'));
Note that if you add the uncaughtException listener after your error event has fired, the exception won't get caught!

writeStream - possible EventEmitter memory leak detected

I'm creating a writestream:
var file = fs.createWriteStream('path', {flags: 'a+', encoding: 'utf16le'});
Using async.queue, I'm queuing this job:
file.write(data, 'utf8');
file.on('error', function(error) {
console.error('ERROR with file stream', error);
});
Getting this warning:
(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Is there a good way to resolve this, without using setMaxListeners(0)?
Node version: 0.10.29
Use file.addListener('error', fn) to add the listener, and file.removeListener() to remove it when the job is done. Listeners exist independently of the registering function, and adding even the identical function stacks, it will get called twice.
function listenerCallback() {
}
file.addListener('error', listenerCallback);
file.removeListener('error', listenerCallback);
The removed listener should be === identical to the one added; adding function(){} then remove function(){} does not cancel the first.
emitter.once() adds a one-shot listener, but since this is used for errors and not fetching the work, it's not appropriate here.
after fetching all the data or error.
remove the listeners
file.removeAllListeners()

possible EventEmitter memory leak detected

I am getting following warning:
(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace:
at EventEmitter.<anonymous> (events.js:139:15)
at EventEmitter.<anonymous> (node.js:385:29)
at Server.<anonymous> (server.js:20:17)
at Server.emit (events.js:70:17)
at HTTPParser.onIncoming (http.js:1514:12)
at HTTPParser.onHeadersComplete (http.js:102:31)
at Socket.ondata (http.js:1410:22)
at TCP.onread (net.js:354:27)
I wrote code like this in server.js:
http.createServer(
function (req, res) { ... }).listen(3013);
How to fix this ?
I'd like to point out here that that warning is there for a reason and there's a good chance the right fix is not increasing the limit but figuring out why you're adding so many listeners to the same event. Only increase the limit if you know why so many listeners are being added and are confident it's what you really want.
I found this page because I got this warning and in my case there was a bug in some code I was using that was turning the global object into an EventEmitter! I'd certainly advise against increasing the limit globally because you don't want these things to go unnoticed.
This is explained in the node eventEmitter documentation
What version of Node is this? What other code do you have? That isn't normal behavior.
In short, its: process.setMaxListeners(0);
Also see: node.js - request - How to “emitter.setMaxListeners()”?
The accepted answer provides the semantics on how to increase the limit, but as #voltrevo pointed out that warning is there for a reason and your code probably has a bug.
Consider the following buggy code:
//Assume Logger is a module that emits errors
var Logger = require('./Logger.js');
for (var i = 0; i < 11; i++) {
//BUG: This will cause the warning
//As the event listener is added in a loop
Logger.on('error', function (err) {
console.log('error writing log: ' + err)
});
Logger.writeLog('Hello');
}
Now observe the correct way of adding the listener:
//Good: event listener is not in a loop
Logger.on('error', function (err) {
console.log('error writing log: ' + err)
});
for (var i = 0; i < 11; i++) {
Logger.writeLog('Hello');
}
Search for similar issues in your code before changing the maxListeners (which is explained in other answers)
By default, a maximum of 10 listeners can be registered for any single event.
If it's your code, you can specify maxListeners via:
const emitter = new EventEmitter()
emitter.setMaxListeners(100)
// or 0 to turn off the limit
emitter.setMaxListeners(0)
But if it's not your code you can use the trick to increase the default limit globally:
require('events').EventEmitter.prototype._maxListeners = 100;
Of course you can turn off the limits but be careful:
// turn off limits by default (BE CAREFUL)
require('events').EventEmitter.prototype._maxListeners = 0;
BTW. The code should be at the very beginning of the app.
ADD: Since node 0.11 this code also works to change the default limit:
require('events').EventEmitter.defaultMaxListeners = 0
Replace .on() with once(). Using once() removes event listeners when the event is handled by the same function.
If this doesn't fix it, then reinstall restler with this in your package.json
"restler": "git://github.com/danwrong/restler.git#9d455ff14c57ddbe263dbbcd0289d76413bfe07d"
This has to do with restler 0.10 misbehaving with node. you can see the issue closed on git here: https://github.com/danwrong/restler/issues/112
However, npm has yet to update this, so that is why you have to refer to the git head.
Node Version : v11.10.1
Warning message from stack trace :
process.on('warning', e => console.warn(e.stack));
(node:17905) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 wakeup listeners added. Use emitter.setMaxListeners() to increase limit
MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 wakeup listeners added. Use emitter.setMaxListeners() to increase limit
at _addListener (events.js:255:17)
at Connection.addListener (events.js:271:10)
at Connection.Readable.on (_stream_readable.js:826:35)
at Connection.once (events.js:300:8)
at Connection._send (/var/www/html/fleet-node-api/node_modules/http2/lib/protocol/connection.js:355:10)
at processImmediate (timers.js:637:19)
at process.topLevelDomainCallback (domain.js:126:23)
After searching for github issues, documentation and creating similar event emitter memory leaks, this issue was observed due to node-apn module used for iOS push notification.
This resolved it :
You should only create one Provider per-process for each
certificate/key pair you have. You do not need to create a new
Provider for each notification. If you are only sending notifications
to one app then there is no need for more than one Provider.
If you are constantly creating Provider instances in your app, make
sure to call Provider.shutdown() when you are done with each provider
to release its resources and memory.
I was creating provider object each time the notification was sent and expected the gc to clear it.
I am getting this warning too when install aglio on my mac osx.
I use cmd fix it.
sudo npm install -g npm#next
https://github.com/npm/npm/issues/13806
I prefer to hunt down and fix problems instead of suppressing logs whenever possible. After a couple days of observing this issue in my app, I realized I was setting listeners on the req.socket in an Express middleware to catch socket io errors that kept popping up. At some point, I learned that that was not necessary, but I kept the listeners around anyway. I just removed them and the error you are experiencing went away. I verified it was the cause by running requests to my server with and without the following middleware:
socketEventsHandler(req, res, next) {
req.socket.on("error", function(err) {
console.error('------REQ ERROR')
console.error(err.stack)
});
res.socket.on("error", function(err) {
console.error('------RES ERROR')
console.error(err.stack)
});
next();
}
Removing that middleware stopped the warning you are seeing. I would look around your code and try to find anywhere you may be setting up listeners that you don't need.
In my case, it was child.stderr.pipe(process.stderr) which was being called when I was initiating 10 (or so) instances of the child. So anything, that leads to attach an event handler to the same EventEmitter Object in a LOOP, causes nodejs to throw this error.
Sometimes these warnings occur when it isn't something we've done, but something we've forgotten to do!
I encountered this warning when I installed the dotenv package with npm, but was interrupted before I got around to adding the require('dotenv').load() statement at the beginning of my app. When I returned to the project, I started getting the "Possible EventEmitter memory leak detected" warnings.
I assumed the problem was from something I had done, not something I had not done!
Once I discovered my oversight and added the require statement, the memory leak warning cleared.
Thanks to RLaaa for giving me an idea how to solve the real problem/root cause of the warning. Well in my case it was MySQL buggy code.
Providing you wrote a Promise with code inside like this:
pool.getConnection((err, conn) => {
if(err) reject(err)
const q = 'SELECT * from `a_table`'
conn.query(q, [], (err, rows) => {
conn.release()
if(err) reject(err)
// do something
})
conn.on('error', (err) => {
reject(err)
})
})
Notice there is a conn.on('error') listener in the code. That code literally adding listener over and over again depends on how many times you call the query.
Meanwhile if(err) reject(err) does the same thing.
So I removed the conn.on('error') listener and voila... solved!
Hope this helps you.
As pointed out by others, increasing the limit is not the best answer. I was facing the same issue, but in my code I was nowhere using any event listener. When I closely looked into the code, I was creating a lot of promises at times. Each promise had some code of scraping the provided URL (using some third-party library). If you are doing something like that, then it may be the cause.
Refer this thread on how to prevent that: What is the best way to limit concurrency when using ES6's Promise.all()?
i was having the same problem. and the problem was caused because i was listening to port 8080, on 2 listeners.
setMaxListeners() works fine, but i would not recommend it.
the correct way is to, check your code for extra listeners, remove the listener or change the port number on which you are listening, this fixed my problem.
I was having this till today when I start grunt watch. Finally solved by
watch: {
options: {
maxListeners: 99,
livereload: true
},
}
The annoying message is gone.
You need to clear all listeners before creating new ones using:
Client / Server
socket.removeAllListeners();
Assuming socket is your client socket / or created server socket.
You can also subscribe from specific event listeners like for example removing the connect listener like this:
this.socket.removeAllListeners("connect");
I was facing the same issue, but i have successfully handled with async await.
Please check if it helps.
let dataLength = 25;
Before:
for (let i = 0; i < dataLength; i++) {
sftp.get(remotePath, fs.createWriteStream(xyzProject/${data[i].name}));
}
After:
for (let i = 0; i < dataLength; i++) {
await sftp.get(remotePath, fs.createWriteStream(xyzProject/${data[i].name}));
}
In my case it was due to not closing the Sequelize connections to database while creating them inside of the async function called with setInterval.
You said you are using process.on('uncaughtException', callback);
Where are you executing this statement? Is it within the callback passed to http.createServer?If yes, different copy of the same callback will get attached to the uncaughtException event upon each new request, because the function (req, res) { ... } gets executed everytime a new request comes in and so will the statement process.on('uncaughtException', callback);Note that the process object is global to all your requests and adding listeners to its event everytime a new request comes in will not make any sense. You might not want such kind of behaviour. In case you want to attach a new listener for each new request, you should remove all previous listeners attached to the event as they no longer would be required using: process.removeAllListeners('uncaughtException');
Our team's fix for this was removing a registry path from our .npmrc. We had two path aliases in the rc file, and one was pointing to an Artifactory instance that had been deprecated.
The error had nothing to do with our App's actual code but everything to do with our development environment.
Adding EventEmitter.defaultMaxListeners = <MaxNumberOfClients> to node_modules\loopback-datasource-juggler\lib\datasource.js fixed may problem :)
Put this in the first line of your server.js (or whatever contains your main Node.js app):
require('events').EventEmitter.prototype._maxListeners = 0;
and the error goes away :)

node.js - request - How to "emitter.setMaxListeners()"?

When I do a GET on a certain URI using the node.js 'request' module;
var options = {uri:"aURI", headers:headerData};
request.get(options, function (error, response, body) {
}
The error message is:
[Error: Exceeded maxRedirects. Probably stuck in a redirect loop.]
and there is also the following message:
"(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit."
How do I setMaxListeners?
I strongly advice NOT to use the code:
process.setMaxListeners(0);
The warning is not there without reason. Most of the time, it is because there is an error hidden in your code. Removing the limit removes the warning, but not its cause, and prevents you from being warned of a source of resource leakage.
If you hit the limit for a legitimate reason, put a reasonable value in the function (the default is 10).
Also, to change the default, it is not necessary to mess with the EventEmitter prototype. you can set the value of defaultMaxListeners attribute like so:
require('events').EventEmitter.defaultMaxListeners = 15;
I use the code to increase the default limit globally:
require('events').EventEmitter.prototype._maxListeners = 100;
This is how I solved the problem:
In main.js of the 'request' module I added one line:
Request.prototype.request = function () {
var self = this
self.setMaxListeners(0); // Added line
This defines unlimited listeners http://nodejs.org/docs/v0.4.7/api/events.html#emitter.setMaxListeners
In my code I set the 'maxRedirects' value explicitly:
var options = {uri:headingUri, headers:headerData, maxRedirects:100};
Although adding something to nodejs module is possible, it seems to be not the best way (if you try to run your code on other computer, the program will crash with the same error, obviously).
I would rather set max listeners number in your own code:
var options = {uri:headingUri, headers:headerData, maxRedirects:100};
request.setMaxListeners(0);
request.get(options, function (error, response, body) {
}
Try to use:
require('events').EventEmitter.defaultMaxListeners = Infinity;
this is Extension to #Félix Brunet answer
Reason - there is code hidden in your app
How to find -
Strip/comment code and execute until you reach error
check log file
Eg - In my case i created 30 instances of winston log Unknowingly and it started giving error
Note : if u supress this error , it will come again afetr 3..4 days
It also happened to me
I use this code and it worked
require('events').EventEmitter.defaultMaxListeners = infinity;
Try it out. It may help
Thanks

Resources