How to check if a directory exists and is not empty?

zip.loadAsync(files).then(function(directory:any){
if (directory.folder("Mary")){ // not sure what to do here
      console.log("fail");
    }
else{
directory.folder("Mary").forEach(function (filename: any) {Console.log(filename);});
    };
}

I try to check if the directory “Mary” does exist and is not null before I do something to every file inside “Mary”. But I am not sure what to do.

To check if a directory exists within a ZIP file using JSZip and then iterate over its files, you can follow a specific approach. The method directory.folder("Mary") will return a folder object or undefined if the folder does not exist. Therefore, you should check whether the folder exists by verifying if it is not undefined.

Here’s how you can modify your code:

Correct Approach:

zip.loadAsync(files).then(function(directory: any) {
  // Check if the folder "Mary" exists
  const maryFolder = directory.folder("Mary");

  // If folder doesn't exist, it will be undefined or null
  if (!maryFolder) {
    console.log("Folder 'Mary' does not exist");
  } else {
    // Folder exists, now you can iterate over the files in "Mary"
    maryFolder.forEach(function(filename: any) {
      console.log(filename);  // Output each file's name in the "Mary" folder
    });
  }
});

Explanation:

  1. directory.folder("Mary"): This attempts to retrieve the folder named “Mary” from the ZIP file. If the folder doesn’t exist, it will return undefined. So, we check if the result is falsy (i.e., undefined or null).
  2. Check if maryFolder is falsy: If maryFolder is falsy, it means the folder does not exist. Otherwise, we proceed to iterate over the files inside the folder.
  3. maryFolder.forEach(...): If the folder exists, you can then use .forEach() to iterate over all files in the folder.

Additional Notes:

  • The .folder() method returns a folder object, but if the folder does not exist, it will return undefined. Checking for this condition is key to avoiding errors.
  • The forEach() method is used to iterate over the files inside the folder. You can access the file names and other details as needed.

Example Output:

If the “Mary” folder exists and contains files, you will see the filenames printed to the console. If the folder doesn’t exist, you will see "Folder 'Mary' does not exist" in the console.