0

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 ?

  • `fs.readdir()` is asynchronous. Maybe use `fs.readdirSync()`? – Barmar Mar 04 '22 at 13:01
  • @Barmar I tried but my console logs didn't get printed so I assumed it wasn't being executed – Rami Ben Romdhane Mar 04 '22 at 13:04
  • It's not reading the last directory. It's just logging the last directory name from `console.log(dirref)` because of https://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue. Change the declaration to `let dirref` – Barmar Mar 04 '22 at 13:04
  • `readdirSync()` doesn't use a callback, it returns the elements as an array. – Barmar Mar 04 '22 at 13:06
  • @Barmar yep you were right.It worked.I guess I should read more javascript docs.many thanks to you – Rami Ben Romdhane Mar 04 '22 at 13:08
  • So in this case should I use `fs.readdir()` or `fs.readdirSync()` or it makes no difference here ? – Rami Ben Romdhane Mar 04 '22 at 13:11
  • @RamiBenRomdhane If your Node app is meant to be use multi-user, eg, an express / koa / web server etc, I would strongly recommend against using `readdirSync`. If your node app is like a utility function run say from console, then `readdirSync` would be fine. So yes, it does make a difference, but it matters based on what your doing. – Keith Mar 04 '22 at 13:32

0 Answers0