Search This Blog

2021/01/10

Reading Files from Path Array ensure synchronous Nature:

we have a fileNames array which contain path to files read.Used bluebird to promisify fs module which makes us available promisified version readFileAsync of readFile.

Created three files 1.txt,2.txt and 3.txt with one two & three inside them inside data folder.Added one,two,three as text inside these three files.

Async Way:


var Promise = require("bluebird");

var fileNames =["data/1.txt","data/2.txt","data/3.txt"]

var fs = Promise.promisifyAll(require("fs"));


var promises = [];

console.log("Started");

for (var i = 0; i < fileNames.length; ++i) {

fs.readFileAsync(fileNames[i],'utf8').then(function(data){

console.log(data);

}).catch(function(err){

console.log(err);

})

}

console.log("Finished");


Output:

Started

Finished

two

one

three


Order of reading files is not maintained.


Using Promise.all


var Promise = require("bluebird");

var fileNames =["data/1.txt","data/2.txt","data/3.txt"]

var fs = Promise.promisifyAll(require("fs"));


console.log("Started");

var promises = [];

for (var i = 0; i < fileNames.length; ++i) {

promises.push(fs.readFileAsync(fileNames[i],'utf8'));

}

Promise.all(promises).then(function(result) {

console.log(result)

console.log("done");

});

console.log("Finished");


Output:

Started

Finished

[ 'one', 'two', 'three' ]

done


Response of reading three files get at once.


Synchronized Way:

var Promise = require("bluebird");

var fileNames =["data/1.txt","data/2.txt","data/3.txt"]

var fs = Promise.promisifyAll(require("fs"));


runLoop = async (cb)=>{

try{

let result =[];

for(let i=0;i < fileNames.length ;i++)

{

console.log("Fetching " + fileNames[i]) + "....";

await new Promise((resolve,reject)=>{

setTimeout(function(){

fs.readFileAsync(fileNames[i],'utf8').then(function(fileContent){

console.log("fileContent",fileContent)

result.push(fileContent)

resolve()

}).catch(function(err){

reject(err)

console.log("err",err);

//throw err;

})

}, 0);

});

}

cb(result)

}catch(ep)

{

console.log("ep",ep);

}

}


runLoop(function(data){

console.log("data",data);

})

 

Output:

Fetching data/1.txt

fileContent one

Fetching data/2.txt

fileContent two

Fetching data/3.txt

fileContent three

data [ 'one', 'two', 'three' ]



reads files in order they present in loop.I tried increasing content of 1.txt yet order remain same.


No comments:

Post a Comment