0

Trying to extract all files from a folder and all it's subdirectories. The content of a directory is called against an external api.

export const extractFiles = (filesOrDirectories) => {
  const files = [];
  const getFiles = (filesOrDirectories) => {
    filesOrDirectories.forEach(async fileOrDirectory => {
      if (fileOrDirectory.type === 'directory') {
        const content = await getDirectoryContent(fileOrDirectory.id);
        getFiles(content);
      } else {
        files.push(fileOrFolder)
      }
    });
  }
  // files should be returned here when it's done. But how do I know when there are no more directories 
};

A recursive function which calls itself when it founds a directory. Otherwise push the file to an array.

But how can I know when there are no more directories to extract?

Joe
  • 4,274
  • 32
  • 95
  • 175

1 Answers1

1

You will know there are no more directories to explore when the function ends.

However it should be noted that since there is asynchronous code inside your extractFiles function, you will have to await the result of any following recursion.

export const extractFiles = async(filesOrDirectories) => {
  const files = [];
  const getFiles = async(filesOrDirectories) => {
    for (const file of filesOrDirectories) {
      if (fileOrDirectory.type === 'directory') {
        const content = await getDirectoryContent(fileOrDirectory.id);
        await getFiles(content);
      } else {
        files.push(fileOrFolder)
      }
    }
  }

  await getFiles(filesOrDirectories)
  return files;
};

const extractedFiles = await extractFiles();

EDIT:

Please note, a forEach will function in unexpected ways when combined with asynchronous code, please refactor to use a for...of loop.

Dane Brouwer
  • 2,827
  • 1
  • 22
  • 30