我的裸露Node.js应用程序看起来像这样(本质上,我经常这么调用Web服务,然后将数据推送到客户端)。大约一天后,即使添加了generator.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)

最佳答案

问题是

Use emitter.setMaxListeners() to increase limit.

并不意味着“创建发射器对象并将发射器.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);

08-15 16:08