Javascript内存泄漏for循环

时间:2017-01-21 14:07:49

标签: javascript node.js memory-leaks garbage-collection

当我在node.js中运行以下代码时,我收到以下错误消息:

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

//Running this code causes program to run out of memory.
for(var i = 0; i < files.length; i++){
        readFile(files[i]); 
}

//log each line of file to console
function readFile(data){
    var lines = fs.readFileSync(data).toString().split('\n');
    for(var k = 0; k < lines.length; k++){
        console.log(lines[k]);
    }
}

但是,如果我更改readFile函数并从for循环中取出console.log(lines[k]),则致命错误就会消失。这是为什么?如何修复原始代码,以免内存不足?

function readFile(data){
    var lines = fs.readFileSync(data).toString().split('\n');
    var string = ''
    for(var k = 0; k < lines.length; k++){
        //console.log(lines[k]);
        string += lines[k];
    }
    console.log(string);  //log the same string outside the loop and the fatal error goes away
}

1 个答案:

答案 0 :(得分:0)

do npm install async --save
var async = require('async');

async.eachSeries(files , filesIteration , finishIteration);

function filesIteration(file , callBack){
    readFile(file , callBack);
}


function readFile(data , cb){
    var lines = fs.readFileSync(data).toString().split('\n');
    for(var k = 0; k < lines.length; k++){
        console.log(lines[k]);
        if(k === lines.length - 1){
            cb();
        }
    }
}

function finishIteration(){
    console.log('all files processed');
}