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'?