Guest User

Untitled

a guest
Jan 29th, 2020
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const MongoClient = require("mongodb").MongoClient;
  2. const fs = require("fs");
  3. const XmlStream = require("xml-stream");
  4.  
  5. const client = new MongoClient("mongodb://localhost:27017", {
  6.   useNewUrlParser: true,
  7.   autoReconnect: true,
  8.   poolSize: 3,
  9.   reconnectTries: 60,
  10.   reconnectInterval: 1000
  11. });
  12.  
  13. client.connect(function(err) {
  14.   if (err) {
  15.     throw new Error("db connection error", err);
  16.   }
  17.   console.log("Connected successfully to server");
  18.  
  19.   let c = 0;
  20.   let Errors = [];
  21.   const db = client.db("opendata");
  22.   const collection = db.collection("edrpou");
  23.  
  24.   function saveData(data) {
  25.     if (data instanceof Object) {
  26.       xml.pause();
  27.       data["$"] ? delete data["$"] : null;
  28.       collection.insertOne(data, (err, res) => {
  29.         if (err) {
  30.           console.error("insertOne: ", err);
  31.           Errors.push(err);
  32.         } else {
  33.           console.clear();
  34.           console.log(data);
  35.           console.info("➕  ", c);
  36.           xml.resume();
  37.         }
  38.       });
  39.     }
  40.   }
  41.  
  42.   let batchTemp = [];
  43.   function saveDataBatch(data) {
  44.     if (data instanceof Object) {
  45.       xml.pause();
  46.       data["$"] ? delete data["$"] : null;
  47.       if (batchTemp.length < 100) {
  48.         batchTemp.push(data);
  49.       } else {
  50.         batchTemp.push(data);
  51.         collection.insertMany(batchTemp, (err, res) => {
  52.           if (err) {
  53.             console.error("insertMany: ", err);
  54.             Errors.push(err);
  55.           } else {
  56.             console.clear();
  57.             console.log(data);
  58.             console.info("➕  ", c);
  59.             batchTemp = [];
  60.             xml.resume();
  61.           }
  62.         });
  63.       }
  64.     }
  65.   }
  66.  
  67.   const streamWrite = fs.createWriteStream("./data/extracted/data.json");
  68.   function saveToFile(data) {
  69.     streamWrite.write(data);
  70.   }
  71.  
  72.   const stream = fs.createReadStream("./data/extracted/edrpou.xml");
  73.   const xml = new XmlStream(stream);
  74.  
  75.   xml.on("endElement: SUBJECT", function(item) {
  76.     saveData(item);
  77.     c++;
  78.   });
  79.  
  80.   xml.on("end", function() {
  81.     // client.close();
  82.     console.error(JSON.stringify(Errors));
  83.     console.log("🔥  END");
  84.   });
  85. });
Add Comment
Please, Sign In to add comment