title: Read content of all files inside a directory in order using node.js
body: <p>I need to loop over files in a given directory, and read content of each file. Like this:</p>
  
  <pre><code>fs.readdir(dirPath, (err, dir)=&gt;{
      for(var i=0; i&lt;dir.length; i++){
          fileName = dir[i];
  
          console.log("A: "+fileName);
          fs.lstat(dir+"\"+fileName, function(err, stats) {
              console.log("B: "+fileName);
          });
      }
    })
  </code></pre>
  
  <p>The output is of the above code is:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>While I would expect the output to be something like:</p>
  
  <pre><code>A: B01.txt
  B: B01.txt
  A: B02.txt
  B: B02.txt
  ... etc
  </code></pre>
  
  <p>How can I sequentially loop over each file of a directory and read it the proper way?</p>
  
  <p><strong>Edit</strong></p>
  
  <p>I updated my code to use statSyn, as follows, as well as adding read file content code:</p>
  
  <pre><code>let  content = "";
  fs.readdir(dirPath, (err, dir)=&gt;{
      for(var i=0; i&lt;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});
              });
          }
      }
  })
  </code></pre>
  
  <p>Now I am getting the following result, please note the "C" lines:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I managed to read all files, but not in order. How can I make sure I read them in order?</p>
  
  <p><strong>The Fix</strong></p>
  
  <p>I ended up using <code>fs.statSync</code> and <code>fs.readFileSync</code> to read files in order. Not to mention using <code>let</code> . Thanks to @x-ray and @Skabbi for their help.</p>