Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
fs.readdir gets executed only at the last iteration of the loop

I'm still new to Javascript and Nodejs and I've been trying to access different files inside different child folders of a common parent. Here's what I mean by that

.
├── _captures (parent folder)
├── _folder1 (child 1)
│   ├── file1.png
│   └── file2.png
├── _folder2 (child 2)
│   ├── file1.png

So I did a for loop that iterates over each child folder and I used a nested fs.readdir which would iterate over each file in the folder.

The problem is that the fs.readdir gets called only after all the iterations and keeps looping on the last folder only.

For example if directories.length is equal to 50 it would loop over the last folder 50 times. Here's the script

var Directories = getDirectories('.\\captures\\');
for (i = 0; i < Directories.length; i++) {
   var dirtest = '.\\VisualTests\\' + Directories[i];
   var dirref = '.\\captures\\' + Directories[i];
   if (!fs.existsSync(dirtest)) {
       fs.mkdirSync(dirtest);
   }
   fs.readdir(dirref, function (err, files) {
       console.log(dirref);
       if (err) {
           console.error("Could not list the directory.", err);
           process.exit(1);
       }
       if (files.length == 0) {
           console.log("test skipped or pending");
       }
       else {
           files.forEach(function (file) {
               console.log(file);
           });
       }
   });


}

How can I make this work ?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!