[英]Node.js memory leak when using .map to create an array
我正在使用 node 向网站重复请求,并尝试调试由此产生的内存泄漏。 通过使用node --inspect server.js
我已经能够猜测这是导致问题的代码(这是 Promise 的一部分,因此最后是“resolve()”):
response.on('end', function () {
//store response in variable
bufferData = Buffer.concat(bufferData);
try {
var bufferDataDecoded = thisProtocol.FeedMessage.decode(bufferData).entity;
} catch (e) {
console.log("Protocol Error: "+e);
resolve([0]);
}
var timeNow = new Date();
var bufferDataMapped= bufferDataDecoded
.map(obj=> {
return obj.item_update
.map(itemu=>{
if ((itemu.quantityOld-itemu.quantityNew) > 0 ){
return {
"resultType": bufferType
,"itemID": itemu.itemID
,"quantityOld": itemu.quantityOld
,"quantityDiff": itemu.quantityNew - itemu.quantityOld
};
}
else return false;
})
});
var bufferDataMapped2= [].concat.apply([],bufferDataMapped);
resolve(bufferDataMapped2);
});
通过查看来自 --inspect 的比较日志并使用 Chrome DevTools 查看,node.js 似乎正在保存这些对象,例如:
{
"resultType": bufferType
,"itemID": itemu.itemID
,"quantityOld": itemu.quantityOld
,"quantityDiff": itemu.quantityNew - itemu.quantityNew
};
...每次程序运行时,而不是在运行后删除旧的,这会很快导致内存溢出。 我在 .map() 中本地创建了变量以试图避免这个问题,但我不确定我做错了什么。 任何想法为什么会发生这种情况?
我缺少一些代码,所以,这是我的结论。 看看这段代码:
bufferData = Buffer.concat(bufferData);
bufferData 是一个全局变量,因此在每次执行中都连接了之前执行的数据。 尝试在每次执行结束时分配 null:
response.on('end', function () {
... rest of the code ...
resolve(bufferDataMapped2);
bufferData = null;
});
但是,为了获得更好的响应,我想查看其余的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.