我得到以下警告:

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

如何解决这个问题?


当前回答

缺省情况下,任何单个事件最多可以注册10个侦听器。

如果这是你的代码,你可以通过:

const emitter = new EventEmitter()
emitter.setMaxListeners(100)
// or 0 to turn off the limit
emitter.setMaxListeners(0)

但如果这不是你的代码,你可以使用技巧来增加全局默认限制:

require('events').EventEmitter.prototype._maxListeners = 100;

当然,你可以关闭限制,但要小心:

// turn off limits by default (BE CAREFUL)
require('events').EventEmitter.prototype._maxListeners = 0;

顺便说一句。代码应该在应用程序的最开始。

ADD:从节点0.11开始,这段代码也可以改变默认限制:

require('events').EventEmitter.defaultMaxListeners = 0

其他回答

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

在我的例子中,它是child.stderr.pipe(process.stderr),当我启动10个(或左右)child实例时,它被调用。因此,任何导致在LOOP中将事件处理程序附加到同一个EventEmitter对象的事情都会导致nodejs抛出这个错误。

我们团队对此的解决方案是从.npmrc中删除注册表路径。rc文件中有两个路径别名,其中一个指向已弃用的Artifactory实例。

这个错误与我们的应用程序的实际代码无关,而是与我们的开发环境有关。

这在节点eventEmitter文档中有解释

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

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

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

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

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

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

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