【问题标题】:How to make NodeJS use all the memory allocated如何让 NodeJS 使用所有分配的内存
【发布时间】:2017-08-21 08:57:08
【问题描述】:

这是我第一次使用大量内存的项目,我观察到一个奇怪的现象。

我正在读取一个大小约为43MB 的excel 文件并将其保存在一个数组中。我想我可能需要寻找一种向客户端流式传输的方法,但我仍然很好奇。

我通过运行node excelParserTool.js --max-old-space-size=10000 来运行我的代码,将10GB 的内存分配给我的程序。

下面是我的代码

let csvWriter = () => {
    let workbook = new Excel.Workbook();

    console.log(`before reading ${JSON.stringify(process.memoryUsage())}`);
    workbook.xlsx.readFile('myfile').then((err, data) => {
        console.log(`after reading ${JSON.stringify(process.memoryUsage())}`);

        workbook.eachSheet((worksheet, sheetId) => {
            let writeStream = fs.createWriteStream(`./sheet${sheetId}`);

            worksheet.eachRow({includeEmpty: true}, (row, rowNumber) => {
                let eachRow = '';

                row.eachCell({includeEmpty: true}, (cell, colNumber) => {

                    if(cell.value !== null && typeof cell.value === 'object'){
                        eachRow += JSON.stringify(cell.value) + ', ';
                    }else if(cell.value === null){
                        eachRow += ', ';
                    }else {
                        eachRow += cell.value + ', ';
                    }
                    console.log(`through each cycle ${JSON.stringify(process.memoryUsage())}`)
                });

                eachRow += '\n';
                writeStream.write(eachRow);
            });
            writeStream.end();
        })
    })
};

关键是对于读取的每一行,我都打印process.memoryUsage(),这样我就可以看到消耗了多少内存。但是当程序死了说Javascript heap out of memory最后内存使用说through each cycle {"rss":1549365248,"heapTotal":1509969920,"heapUsed":1479087128,"external":3724116}

Heaptotal 和使用的堆只有 1.5Gb 左右,远低于我为程序分配的空间。此外,当我看到我的计算机统计信息时,仍有超过 7gbs 可用。这是为什么呢?

【问题讨论】:

    标签: node.js memory memory-management


    【解决方案1】:

    你在错误的地方设置了内存标志

    节点 [选项] [ -e 脚本 | script.js ] [参数]

    所以在你的情况下应该是node --max-old-space-size=10000 excelParserTool.js

    【讨论】:

      猜你喜欢
      • 2012-07-28
      • 1970-01-01
      • 2020-03-24
      • 2020-11-14
      • 2018-03-23
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多