(节点:6261)MaxListenersExceededWarning:可能检测到EventEmitter内存泄漏

时间:2018-10-31 06:23:56

标签: node.js apple-push-notifications

我在nodejs应用上收到此错误: 节点版本:v8.11.1

(node:6261) MaxListenersExceededWarning: Possible EventEmitter memory leak
detected. 11 wakeup listeners added. Use emitter.setMaxListeners() to increase
limit

我有一个非常简单的代码,可以使用node-apn将通知推送到IOS设备。 代码运行正常,我也在设备上收到推送通知

var express               = require('express')
  , serverPort            = 6900
  , app                   = express()
  , http                  = require('http')
  , https                 = require('https')
  , fs                    = require('fs')
  , apn                   = require('apn')
;

var server = http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello!');
  res.end();
});

server.listen(serverPort, (err) => {

  if(err) { return console.log("Something bad happened", err); }
});

var apnOptions = {

  token: {
  },
  production: false 
};

var apnProvider = new apn.Provider(apnOptions);
var note        = new apn.Notification();

note.expiry     = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.badge      = 3;
note.sound      = "ping.aiff";
note.alert      = "\uD83D\uDCE7 \u2709 You have a new message";
note.payload    = { 'messageFrom': 'John Appleseed' };
note.topic      = "com.example.test";

apnProvider.send(note, '6A752501A5DAFF9DCSFRE56C5B0E699385CD14B586CEF4B9C5012DDA4').then( (result) => {

  console.log(result); 
});

这里的问题是APN代码,因为一旦我注释了APN代码,我就不会再遇到此错误了。 谁能知道我的代码有什么问题吗?我觉得我已经在这里做了所有事情,但仍然面临着这个问题。

2 个答案:

答案 0 :(得分:1)

有两种解决方案。两者都与更新最大侦听器数量有关,都应在代码的开头添加。

1-您可以为以下事件监听器设置0,这很冒险,因为您基本上是在取消限制:

const emitter = new EventEmitter()
emitter.setMaxListeners(0)

2-全局修复错误,将最大值设置为最大值

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

参考文献1:https://nodejs.org/docs/v0.4.7/api/events.html#emitter.setMaxListenershttps://nodejs.org/docs/v0.4.7/api/events.html#emitter.setMaxListeners

参考文献2:possible EventEmitter memory leak detected

答案 1 :(得分:0)

node-apnseveral issues,请尝试使用node-apn-http2

npm install node-apn-http2

替换, apn = require('apn')

, apn = require('node-apn-http2')