Here is my code which will read XML files and import the data to MongoDb. Do you have any comments on my code?
const fs = require('fs');
const xml2js = require('xml2js');
const log = console.log;
const path = require( "path" );
const folderPath = 'D:/Data';
const folder = folderPath;
fs.readdirSync(folder).forEach(file => {
const extname = path.extname(file);
const filename = path.basename(file, extname);
const absolutePath = path.resolve(folder, file);
const parser = new xml2js.Parser({
mergeAttrs: true,
explicitArray: false
});
fs.readFile(absolutePath, (err, data) => {
parser.parseString(data, (err, result) => {
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("myDb");
dbo.collection("entity").insertMany(result, function (err, res) {
if (err) throw err;
db.close();
});
});
});
});
});
I tested that it works for few files but for hundreds of files, it can throw an error.