我的裸骨Node.js应用程序看起来像这样(基本上我经常调用一个Web服务,并将数据推送到客户端)大约一天后,即使添加了发射器,我也会得到以下运行错误.setMaxListeners(0)。我很确定我的代码没有任何内存泄漏。有什么建议吗?
/*
* Server setup
*/
var querystring = require('querystring');
var xml2js = require('xml2js');
var parser = new xml2js.Parser();
var eyes = require('eyes');
var http = require('http');
var app = http.createServer(handler);
var io = require('socket.io').listen(app);
var emitter = new (require('events').EventEmitter);
emitter.setMaxListeners(0);
io.set('log level', 0);
app.listen(8080);
function handler(req, res){
res.writeHead(200, {'Content-Type':'text/html'});
res.end('Test');
}
/*
* Global data object
*/
var xmlData= '';
var cache = [];
/*
* web service info
*/
var postData = querystring.stringify({
'index' : '',
'type' : '-1',
});
var options = {
host: 'localhost',
path: '/WebService.asmx',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var getData = function(){
// Web Service Request Obj
var webServiceReq = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
xmlData += chunk;
}).on('end', function() {
parser.parseString(xmlData, function(err, data){
cache = JSON.parse(data['#']);
});
io.sockets.emit('message', { "data": cache});
});// end res.on('end')
});
webServiceReq.write(postData);
webServiceReq.end();
}
// grab the info every 10 seconds
setInterval(getData, 5000);
// emit the latest data when client initially connects
io.sockets.on('connection', function (socket) {
// emit the data
socket.emit('message', {"data": cache});
});
错误:
(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace
at Parser.EventEmitter.addListener (events.js:168:15)
at Parser.exports.Parser.Parser.parseString (C:\WebApplications\WebApp\scripts\node_modules\xml2js\lib\xml2js.js:197:14)
at Parser.__bind [as parseString] (C:\WebApplications\WebApp\scripts\node_modules\xml2js\lib\xml2js.js:6:61)
at IncomingMessage.getData (C:\WebApplications\WebApp\scripts\nodeService.js:87:20)
at IncomingMessage.EventEmitter.emit (events.js:115:20)
at IncomingMessage._emitEnd (http.js:366:10)
at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
at Socket.socketOnData [as ondata] (http.js:1356:20)
at TCP.onread (net.js:410:27)
答案 0 :(得分:5)
问题在于
Use emitter.setMaxListeners() to increase limit.
并不意味着'创建发射器对象并将emitter.setMaxListeners(0)添加到您的代码'。字'发射器'在这里指的是从EventEmitter继承的任何对象,例如服务器,进程,请求等。在您的情况下,您在显示的代码中有2个发射器:app和io。你应该写的是:
var http = require('http');
var app = http.createServer(handler);
var io = require('socket.io').listen(app);
app.setMaxListeners(0);
io.setMaxListeners(0);
io.set('log level', 0);
app.listen(8080);
答案 1 :(得分:2)
如果您想全局增加限额,请将该行放在应用的开头:
require('events').EventEmitter.prototype._maxListeners = 100;