簡體   English   中英

使用 .map 創建數組時的 Node.js 內存泄漏

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM