I have problem with memory leak in nodejs when I added gzip support. I have wrote some code for tests. In code below I use zlib and I don't know why I have memory leak. How I can improve this code to avoid memory leaking ? Anybody can help me ?
var
zlib = require('zlib'),
crypto = require('crypto');
var cacheList = {
article: {},
};
var timeoutId1, timeoutId2
console.log('process.pid: '+ process.pid);
clean = function()
{
var time = new Date().getTime();
timeoutId1 = setTimeout(function() { clean() }, 5000);
var countDeleted = 0;
for (id in cacheList.article) {
if (cacheList.article[id] && cacheList.article[id].timeExpire + 5000 < time) {
delete cacheList.article[id];
countDeleted++;
}
}
console.log('deleted: ' + countDeleted);
}
run = function()
{
var time = new Date().getTime();
timeoutId1 = setTimeout(function() { run() }, 5);
var md5 = crypto.createHash('md5');
md5.update('' + time);
var id = md5.digest('hex');
//console.log('id: ' + id);
var text = id+id+id+id+id+id+id+id +id+id+id+id+id+id+id+id +id+id+id+id+id+id+id+id +id+id+id+id+id+id+id+id +id+id+id+id+id+id+id+id +id+id+id+id+id+id+id+id +id+id+id+id+id+id+id+id +id+id+id+id+id+id+id+id;
zlib.gzip(text, function(err, result) {
if (!err) {
cacheList.article[id] = {
timeExpire: time + 10000,
data: text,
datagzip: result,
};
}
});
}
timeoutId1 = setTimeout(function() { run() }, 3000);
timeoutId2 = setTimeout(function() { clean() }, 5000);
change your two last lines to
timeoutId1 = run()
timeoutId2 = clean()
Since you already have the functions calling the setTimeout, by having another setTimeout, you are telling it to run another instance of that function (which in turn calls itself, so now you have it running twice, and so on).