Below is the code
const fs = require('fs');
const xml2js = require('xml2js');
const log = console.log;
const path = require( "path" );
const folderPath = 'Data';
const folder = folderPath;
let counter = 0;
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
});
counter++;
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("customers").insertOne(result, function (err, res) {
if (err) throw err;
console.log("XML Uploaded Succesfully : " + absolutePath);
db.close();
});
});
});
});
});
console.log("Number of XML inserted: " + counter);
=============================================================
Above code works Perfectly it reads all the files that are present in Data folder
i want to limit this
i.e Suppose i have 10 files in Data folder but want to read only first 5 files and after reading the first 5 files i want it to move in another folder say it "Done Reading"
2
Answers
I hope it will do that what you want to do
Use the index in forEach method it will provide you the file position from the array
based on the do one if condition you can perform task