I have multiple json file in a folder.
What I have to achieve ?
I have to write a function, to traverse through all files inside that folder, and return a JSON array with filename as key and content as value.
[ {jsonFileName1:content1}, {jsonFileName2:content2}, {jsonFileName3:content3} ]
Special condition
Each file content contains few special characters like $,{.
For Example :
{
"_id": "${obj2.result.id}",
"someKey" : ${obj1.result.someValue}
}
What Problem I am facing
While parsing file content, it is throws exception.
Note : I cant enclose ${obj1.result.someValue}
in quotes.
Code :
function readFileAsync(){
const pathUrl = pathToDir;
readFileNamesInDir(pathUrl)
.then((fileNames)=>{
console.log(fileNames);
const pTempArr = [];
fileNames.forEach(function(filename) {
pTempArr.push( readAndGetFilesContent(pathUrl, filename) );
});
return Promise.all( pTempArr );
})
.then((response)=>{
console.log(response);
})
.catch((err)=>{
console.log(err);
});
}
function readFileNamesInDir(dirPath){
return new Promise((resolve, reject)=>{
fs.readdir(dirPath, function(err, filenames) {
if (err) {
reject(err);
return;
}
resolve(filenames)
});
});
}
function readAndGetFilesContent(pathToFile, fileName){
return new Promise((resolve, reject)=>{
fs.readFile(pathToFile + fileName,'utf8', function(err, content) {
if (err) {
reject(err);
return;
}
const tmp = {};
tmp[fileName] = content;
resolve( tmp );
});
});
}
via Sunil Sharma
No comments:
Post a Comment