当我使用node-imap模块时,这个问题进入我的脑海。 (请参阅https://github.com/mscdex/node-imap)如果removeAllListeners()未被调用,EventEmitter是否会导致内存泄漏?
在此模块中,fetch()方法将调用一个回调函数,该函数会为其提供一个ImapFetch()对象,您的代码可以侦听“消息”事件。消息事件轮流将每个对象的消息对象与需要侦听的事件进行传递。
下面是从该模块的示例代码:
imap.fetch(results,
{ headers: ['from', 'to', 'subject', 'date'],
cb: function(fetch) {
fetch.on('message', function(msg) {
console.log('Saw message no. ' + msg.seqno);
msg.on('headers', function(hdrs) {
console.log('Headers for no. ' + msg.seqno + ': ' + show(hdrs));
});
msg.on('end', function() {
console.log('Finished message no. ' + msg.seqno);
});
});
}
}, function(err) {
if (err) throw err;
console.log('Done fetching all messages!');
imap.logout();
}
);
如图所示,听众永远不会除去。如果进程在运行一次后立即退出,这可能没有问题。但是,如果进程长时间运行,代码会重复执行,会导致内存泄漏吗?即因为侦听器不会被删除,所以它们保留所有的提取和消息对象,即使它们只用于命令的持续时间。
我的理解不正确?
你说得对。我错误地认为事件监听器可能会增加对msg的额外引用,但实际上,这并未发生。 – wciu 2013-07-11 20:30:05