简体   繁体   English

Node JS读取文件插入到mongo db

[英]Node JS read file insert to mongo db

I have a text file with this content我有一个包含此内容的文本文件

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"

I want to insert it to my mongo db with this format我想用这种格式将它插入到我的 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
},

I've been trying to find node packages that could help but almost all file reader packages can only read the file and not allow line by line editing.我一直在尝试寻找可以提供帮助的节点包,但几乎所有文件阅读器包都只能读取文件而不允许逐行编辑。 For example if the next line is indented it should merge with previous line.例如,如果下一行缩进,它应该与上一行合并。

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
}

you can use this approach to read your directory and store data this is just a basic approach to insert data from text file to databse.您可以使用这种方法来读取您的目录和存储数据这只是将数据从文本文件插入数据库的基本方法。 i hopw this may help you我希望这对你有帮助

This will be a two step process.这将是一个两步过程。 The first will be parsing your file.第一个是解析你的文件。 It doesn't appear to be in any common standard (that I'm aware of) so you'll likely need to write this yourself.它似乎没有任何通用标准(据我所知),因此您可能需要自己编写。

The second part will be writing files to a mongodb. This is a separate issue, though if you follow the documentation it's fairly straightforward.第二部分是将文件写入 mongodb。这是一个单独的问题,但如果您按照文档进行操作,它会相当简单。 I'd suggest you try these things and then ask again if you have any problems.我建议你尝试这些事情,然后再问你是否有任何问题。

Edit: Here's the file parsed to a js object: https://jsfiddle.net/cyksd7o3/编辑:这是解析为 js object 的文件: 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM