Sunday, 12 March 2017

Read content of all files in directory using node.js

I need to loop over files in a given directory, and read content of each file. Like this:

fs.readdir(dirPath, (err, dir)=>{
    for(var i=0; i<dir.length; i++){
        fileName = dir[i];

        console.log("A: "+fileName);
        fs.lstat(dir+"\"+fileName, function(err, stats) {
            console.log("B: "+fileName);
        });
    }
  })

The output is of the above code is:

A: B01.txt
A: B02.txt
A: B03.txt
A: B04.txt
A: B05.txt
B: B05.txt
B: B05.txt
B: B05.txt
B: B05.txt
B: B05.txt

While I would expect the output to be something like:

A: B01.txt
B: B01.txt
A: B02.txt
B: B02.txt
... etc

How can I sequentially loop over each file of a directory and read it the proper way?



via Lamar

No comments:

Post a Comment