当我添加gzip支持时,我在nodejs中遇到内存泄漏问题。我已经为测试编写了一些代码。在下面的代码中我使用zlib,我不知道为什么我有内存泄漏。 我如何改进此代码以避免内存泄漏?有人可以帮帮我吗?
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);
答案 0 :(得分:0)
将最后两行更改为
timeoutId1 = run()
timeoutId2 = clean()
由于你已经有调用setTimeout的函数,通过另一个setTimeout,你告诉它运行该函数的另一个实例(它反过来调用自己,所以现在你运行它两次,依此类推)。