Finding a Drive App folder by path

Using DriveApp service, sometimes you want to specify a folder path like /abc/def/ghi and get the folder object of 'ghi'. With the old DocsList service this was possible, but it doesn't exist with the Drive service.

Here's a handy function to do that.

function getDriveFolderFromPath (path) {
  return (path || "/").split("/").reduce ( function(prev,current) {
    if (prev && current) {
      var fldrs = prev.getFoldersByName(current);
      return fldrs.hasNext() ? fldrs.next() : null;
    }
    else {
      return current ? null : prev;
    }
  },DriveApp.getRootFolder());
}

The opposite - starting with a folder and figuring out its path is probably  best done recursively

function getDrivePathFromFolder (folder,optPath) {

  var path = optPath || '/';
  if (!folder) return '';
  
  if (folder.getId() === DriveApp.getRootFolder().getId()) {
    return path;
  }
  else {
    return getDrivePathFromFolder(folder.getParents().next() , '/' + folder.getName() + path);
  }

}




Although if you really wanted to, you could do it like this

function getDrivePathFromFolderAlt (folder) {

  return pass_(folder,[]).reduce(function(p,c) { return c + '/' + p; } ,'/' );

  function  pass_ (f,p) {
    if (f && f.getId() !== DriveApp.getRootFolder().getId()) {
      p.push(f);
      return pass_ (f.getParents().next(),p);
    }
    return p;
  }
}
Here's a test going back and forwards between the two a couple of times - will give you the folder name 'tasks'
 Logger.log(getDriveFolderFromPath(getDrivePathFromFolder(getDriveFolderFromPath("/datahandler/driverdrive/tasks"))).getName());

For help and more information join our forum,follow the blog or follow me on twitter .

Comments