我得到以下警告:

(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)

我在server.js中写了这样的代码:

http.createServer(
    function (req, res) { ... }).listen(3013);

如何解决这个问题?


当前回答

有时,这些警告发生在我们没有做过的事情,而是我们忘记做的事情!

当我用npm安装dotenv包时遇到了这个警告,但在我在应用程序开始添加require('dotenv').load()语句之前就被打断了。当我回到项目时,我开始得到“可能的EventEmitter内存泄漏检测到”警告。

我以为问题出在我做了什么,而不是我没做什么!

一旦我发现了我的疏忽并添加了require语句,内存泄漏警告就清除了。

其他回答

直到今天我开始监视咕噜咕噜的时候,我才开始这样做。最终由

watch: {
  options: {
    maxListeners: 99,
    livereload: true
  },
}

烦人的信息消失了。

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();
    }

删除该中间件将停止您所看到的警告。我会查看您的代码,并尝试找到您可能设置了不需要的侦听器的任何地方。

添加EventEmitter.defaultMaxListeners = <MaxNumberOfClients>到node_modules\loop -datasource-juggler\lib\datasource.js修复了可能的问题:)

这在节点eventEmitter文档中有解释

这是什么版本的Node ?你还有其他代码吗?这不是正常的行为。

简而言之,它:process.setMaxListeners(0);

另见:node.js - request -如何“emitter.setMaxListeners()”?

公认的答案提供了如何增加限制的语义,但正如@voltrevo指出的那样,警告是有原因的,您的代码可能存在错误。

考虑以下有bug的代码:

//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');
}

现在观察添加监听器的正确方法:

//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');
}

在更改maxListeners之前搜索代码中的类似问题(在其他答案中有解释)