0

I have a situation where I need to read all the files in a directory and all its subdirectories. I wrote a basic function:

Although this is in React-Native, I'm not sure that matters (or maybe there is a react-native solution).

let fileList = [];

const readDir = async (dir) => {

  // This line simply reads the contents of a directory, creating an array of strings
  // of all the files and directories inside 'dir'.
  const items = await FileSystem.readDirectoryAsync(dir); 

  items.forEach(async (item) => {
    const f = await FileSystem.getInfoAsync(item); // Gets basic information about the item
    if (f.isDirectory === true) {
      readDir(f.uri); // f.uri is the location of the new directory to read
    } else {
      // runs if the item is a file
      console.log("f.uri: ", f.uri);
      fileList.push(f.uri); // A global variable
    }
  })
};

const parentDirectory = "parent_folder";
readDir(parentDirectory);

// Do more stuff here once all files have been read and added to 'fileList'

This seems to partially work as all the files in all the subdirectories are consoled out from inside the else {...} segment.

However, how can I know the loop is complete so I can continue the script and use 'fileList'?

John
  • 497
  • 2
  • 16

1 Answers1

1

Don't use forEach with async they don't work together and you can't await the loop. Use a standard for .. of loop, which works nicely with async/await

const readDir = async (dir) => {
  const items = await FileSystem.readDirectoryAsync(dir);

  for (let item of items) {
    const f = await FileSystem.getInfoAsync(item); 
    if (f.isDirectory === true) {
      await readDir(f.uri); 
    } else {
      console.log("f.uri: ", f.uri);
      fileList.push(f.uri); 
    }
  }
}

And as readDir is async as well, you have of course either to await it also, or use then to continue once it is finished

async function foo() {
   const parentDirectory = "parent_folder";
   await readDir(parentDirectory);
   //do some other stuff once readdir is finished.
}

or

const parentDirectory = "parent_folder";
readDir(parentDirectory).then(_ => {
   //do some other stuff once readdir is finished.

}
derpirscher
  • 14,418
  • 3
  • 18
  • 35