How would you create a sub directory for an existing FileFolder object?

If a user has chosen a directory to say, export a rendition and they also want some renditions in a sub directory how would you make that subdirectory?

For example, user picks a folder:

var outputFolder = await fileSystem.getFolder();

But in that directory they also want to export to a sub directory. They provide a string of the subdirectory name, “icons”.

Can I pass in a path to get a sub directory object? And if it’s not created will this create it?

var outputFolder = await fileSystem.getFolder(); // user picks folder
var subFolder = outputFolder.getEntry("icons"); // i get subfolder

Or could I get the outputFolder.nativePath and tack on the sub directory?

var subFolder = fileSystem.getFolder(outputFolder.nativePath + "/icons/"); // no prompt

This seems to work.

/**
 * Gets a reference to a subfolder from a folder object. Creates it if it doesn't exist.
 * Does not support nested directories at this time
 * @param {File} folder file of type folder  
 * @param {String} subfolderName name of sub folder
 * @param {Boolean} create if true creates the directory if it doesn't exist
 * @returns {File|Error} returns the folder or an error object
 */
async function getSubFolder(folder, subfolderName, create = true) {
  var subfolder = null;

  try {
    subfolder = (await folder.getEntries()).find(entry => entry.name.includes(subfolderName));

    if (subfolder==null || subfolder.isFolder==false) {
      if (create) {
        subfolder = await folder.createFolder(subfolderName);
      }
    }
  }
  catch(fileError) {
    return fileError;
  }

  return subfolder;
}
1 Like