簡體   English   中英

nodejs用盡內存處理csv文件

[英]nodejs running out of memory processing csv files

我已經閱讀了許多有關nodejs內存不足的SO問題,但是我還沒有發現任何聽起來與我的情況類似的東西。

我正在嘗試在250個csv文件中處理大約20GB的數據(因此〜80MBs /文件)。 使用節點v5.9.1在具有90GB可用內存的服務器上以--max-old-space-size=8192啟動節點腳本。 經過9分鍾的處理后,腳本退出並顯示內存不足錯誤。

我是Node編程的新手,但我想我寫了腳本來一次處理一行數據,而不在內存中保留任何內容。 但是似乎某些對象引用被某種東西保留,因此腳本正在泄漏內存。 這是完整的腳本:

var fs = require('fs');
var readline = require('readline');
var mongoose = require('mongoose');

mongoose.connect('mongodb://buzzard/xtra');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));

var DeviceSchema = mongoose.Schema({
    _id: String,
    serial: String
});

var Device = mongoose.model('Device', DeviceSchema, 'devices');

function processLine(line) {
    var serial = line.split(',')[8];

    Device({
        _id: serial,
        serial: serial
    }).save(function (err) {
        if (err) return console.error(err);
    });
}

function processFile(baseDir, fileName) {
    if(!fileName.startsWith('qcx3'))
        return;

    var fullPath = `${baseDir}/${fileName}`;

    var lineReader = readline.createInterface({
      input: fs.createReadStream(fullPath)
    });

    lineReader.on('line', processLine);
}

function findFiles(rootDir) {
  fs.readdir(rootDir, function (error, files) {
    if (error) {
        console.log(`Error: ${error}` );
        return
    }

    files.forEach(function (file) {
        if(file.startsWith('.'))
            return;

        var fullPath = `${rootDir}/${file}`;

        fs.stat(fullPath, function(error, stat) {
            if (error) {
                console.log(`Error: ${error}` );
                return;
            }

            if(stat.isDirectory())
                dir(fullPath);
            else
                processFile(rootDir, file);
        });
    });
  })
}  


findFiles('c://temp/logs/compress');

我還注意到,當我在一個可以完全完成處理的較小測試集上運行腳本時,該腳本不會在最后退出。 一直掛在那里,直到我按ctrl + c為止。 這可能以某種方式相關嗎?

我究竟做錯了什么?

  1. 該腳本沒有退出,因為您已經打開了與貓鼬的連接,在處理完所有文件之后,您應該關閉連接,腳本將完成。
  2. 您有使用流的正確想法,但我認為您在途中錯過了一些東西,建議您在下面的文章中更新streamInterface和事件。 https://coderwall.com/p/ohjerg/read-large-text-files-in-nodejs

  3. 問題的另一個來源可能是mongodb,看來您做了很多插入操作,這可能與耗盡內存的mongodb的最大I / O有關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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