0

I am a bit confused on working with fs and async/await. I have a folder called tests that contains 6 folders and each one of them contains lots of images. I need to loop through each image and save its filename into an array. This is the folders structure:

|-tests
 |---test1
 |---test2
 |---test3
 |---test4
 |---test5
 |---test6

This is the code I wrote:

let array = [];

fs.readdir(sourcePathDesktopWin,  (err, folders) => {
  console.log('folders: ', folders);
  folders.forEach( (folder) => {
    fs.readdir(
      `${sourcePathDesktopWin}/${folder}/`,
       (err, files) => {
        files.forEach( async (file) => {
          await array.push(file);
        });
      }
    );
  });
});

console.log('array: ', array);

The console.log appears empty because it runs before the fs functions have finished. I have 2 questions here:

  1. how do I make it so the console.log is fired after the fs functions have finished running?
  2. What is a better way to write this function?

Thank you.

Andrea D_
  • 434
  • 3
  • 11

0 Answers0