读取大文件并逐行插入 Node.JS 中的数据库

Reading large file and inserting line by line into database in Node.JS

本文关键字:JS 数据库 Node 插入 文件 逐行 读取      更新时间:2023-09-26

我有一个非常大的文件,其中包含大量JSON字符串(超过100K),每行都有一个字符串。

我想阅读每一行,将其插入数据库,在插入项目后,我想使用初始插入中的基本信息更新另一个数据库中的另一个文档。 而且由于我是nodejs新手,所以我很难理解我做错了什么。 这是我到目前为止所拥有的。

var lineReader - require("line-reader");
lineReader.eachLine(filePath, function(line, last){
    if(count == 1){
        asyncAdd(JSON.parse(line));
    }
})}
var counter = 0;
function asyncAdd(jsonString){
async.waterfall([
        //this function calls the inserter
    function(callback){
        counter++;
        addJson(jsonString, function(doc){
            callback(null, doc);
            console.log("Added " + counter);
        })
    },
    //This function calls the indexing function
    function(doc, callback){
        console.log("indexing: " + counter);
        updateDBIndex(doc, function(err, savedDocument){
            callback(err, savedDocument);
        });
    }
    ],
    function(err, results){
        if(err){
            return console.error("Error " + err);
        }
        console.log("indexed " + counter);
    });
     }

基本上,如果我的文件看起来像:

{"_id": "1", "item":"glove", "color": "red"}'n
{"_id": "4", "item":"hat", "color" : "red"}'n
{"_id": "6", "item":"hat","color" : "blue"}'n

我希望输出看起来像这样,添加 1索引 1索引 1添加 2索引 2索引 2添加 3索引 3索引 3

任何帮助将不胜感激! 谢谢!

你可以尝试遵循代码片段

var lineReader = require("line-reader");
var lineNumber = 0;
lineReader.eachLine(filePath, function (line, last) {
  asyncAdd(JSON.parse(line), lineNumber); // current line number
  lineNumber++; // increment for next one
});
function asyncAdd(jsonString, lineNum/*additional parameter*/) {
  async.waterfall([
      //this function calls the inserter
      function (callback) {
        addJson(jsonString, function (doc) {
          callback(null, doc);
          console.log("Added " + lineNum);
        })
      },
      //This function calls the indexing function
      function (doc, callback) {
        console.log("indexing: " + lineNum);
        updateDBIndex(doc, function (err, savedDocument) {
          callback(err, savedDocument);
        });
      }
    ],
    function (err, results) {
    if (err) {
      return console.error("Error " + err);
    }
    console.log("indexed " + lineNum);
  });
}

希望它有效,原版有点不完整。