Lamar
Lamar

Reputation: 1849

Read content of all files inside a directory in order 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?

Edit

I updated my code to use statSyn, as follows, as well as adding read file content code:

let  content = "";
fs.readdir(dirPath, (err, dir)=>{
    for(var i=0; i<dir.length; i++){
        let fileName = dir[i];
        let filePath=dirPath+"/"+fileName;
        console.log("A: "+fileName);
        stat = fs.statSync(filePath);
        if(stat.isFile()){
            console.log("B: "+fileName);
            fs.readFile(filePath, 'utf8', function (err,data) {
                if (err) {
                    console.log(err);
                }
                console.log("C: "+ fileName);
                mainWindow.webContents.send('getContent' , {msg:data});
            });
        }
    }
})

Now I am getting the following result, please note the "C" lines:

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

I managed to read all files, but not in order. How can I make sure I read them in order?

The Fix

I ended up using fs.statSync and fs.readFileSync to read files in order. Not to mention using let . Thanks to @x-ray and @Skabbi for their help.

Upvotes: 4

Views: 5257

Answers (2)

Skabbi
Skabbi

Reputation: 436

You getting the output

B: B05.txt

over and over again seems to be a simple scoping issue.

Try using "let fileName".

Upvotes: 0

x-ray
x-ray

Reputation: 3329

fs.lstat is an asynchronous function. You can use fs.lstatSync instead to get the desired behaviour.

Upvotes: 1

Related Questions