Node JS读取文件插入到mongodb数据库

Node JS read file insert to mongo db

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

我有一个文本文件,内容如下

title: A, alert: notice, desc: Starting
title: B, alert: notice, desc: Process Step 1 and 2
 Step 1 - Execute
 Step 2 - Log
title: C, alert: notice, desc: "Ending"

我想把它插入到我的mongo数据库中,格式为

{
 title: A,
 alert: notice,
 desc: Starting
},
{
 title: B,
 alert: notice,
 desc: Process Step 1 and 2 Step 1 - Execute Step 2 - Log
},
{
 title: C,
 alert: notice,
 desc: Ending
},

我一直在试图找到节点包,可以帮助,但几乎所有的文件阅读器包只能读取文件,不允许逐行编辑。例如,如果下一行缩进,它应该与前一行合并。

const fs = require('fs');
const rl = require('readline');
const mongoose = require('mongoose');
let readline = [];
let readlinesplit = [];
let finalarrobj = [];
let keyarr = [
  'variable',
  'identification',
  'value',
  'unit',
  'status',
  'date',
  'time'
];
let splitline = [];
let filenamearr = []
let getfile;
let scSchema = new mongoose.Schema(
  {
    variable: {
      type : String
    },
    identification: {
      type : String
    },
    value: {
      type : String
    },
    unit: {
    },
    status: {
      type : String 
    },
    date: {
      type: Date
    },
    time: {
      type: Date
    }  
  }
)
const SC = mongoose.model('SC', scSchema);
try {
  fs.readdir('D:/scnner_data/public', (err, data) => {
    if (err) throw err;
    data.forEach((element) => {
      if (element.match(/SC/)) {
        filenamearr.push(element);
      }
    });
    filenamearr.map(async (element) => {
      getfile = fs.createReadStream(`public/${element}`);
      readline = rl.createInterface({
        input: getfile,
        crlfDelay: Infinity 
      });
      for await (let line of readline) {
        splitline.push(line.split(''n'));
      };
      splitline.forEach((element) => {
        readlinesplit.push(element[0].split(';'));
      });
      for (let i = 0; i < readlinesplit.length; i++) {
        readobj = {};
        for (let j = 0; j < keyarr.length; j++) {
          readobj[keyarr[j]] = readlinesplit[i][j];
        };
        finalarrobj.push(readobj);
      };
      try {
        SC.insertMany(finalarrobj);
        console.log('data inserted for SC');
      } catch (error) {
        throw  error.message;
      }
    });
  })
} catch(e) {
   throw e.message
}

可以使用这种方法读取目录并存储数据这只是将数据从文本文件插入数据库的一种基本方法。我希望这对你有帮助

这将是一个两步过程。第一步是解析文件。它似乎没有任何通用标准(据我所知),所以你可能需要自己写。

第二部分将向mongodb写入文件。这是一个单独的问题,但如果您遵循文档,它是相当简单的。我建议您试试这些方法,如果有问题再来问我。

编辑:下面是解析为js对象的文件:https://jsfiddle.net/cyksd7o3/

var fileInput = 'title: A, alert: notice, desc: Starting'ntitle: B, alert: notice, desc: Process Step 1 and 2  Step 1 - Execute Step 2 - Log 'ntitle: C, alert: notice, desc: "Ending"';
var parseFile = function(input){
		var rows = input.split(''n');
    var returnObj = [];
    for (var i=0; i < rows.length; i++){
    		var currRow = rows[i];
        returnObj.push(getDataObject(currRow));
    }
    return returnObj;
};
var getDataObject = function(inputRowString){
		var newObject = {};
		var propSplit = inputRowString.split(',');
    for (var i = 0; i < propSplit.length; i++){
    		var currSplit = propSplit[i];
        var keyValue = currSplit.split(':');
        newObject[keyValue[0].replace(/'s/g,'')] = keyValue[1];
    }
    return newObject;
};
console.dir(parseFile(fileInput));