The usual way to access files and folders on Drive from Apps Script is via their ID, yet on other platforms we’re more used to using file and folder paths. This can be a bit random on Drive because
- files can have multiple parent folders
- more than 1 file with the same name can exist in the same folder
However, most of us don’t really do that so I’m still preferring to try to work with file and folder paths on Drive.
Another issue is that the file and folder iterators in DriveApp are not real V8 Iterators, so you can’t do things like for (x of files) or Array.from(files). I don’t like that either.
So this is a small library (bmFolderFun) to help fix all that.
Apps Script Initialization
There’s actually a class in the library, but you can’t expose a class from a library in Apps Script for some reason, so you can get a new instance of the class like this. Note that you pass your DriveApp to it. This is because all my libraries nowadays are, by design, dependency free. You’ll need to leave the comment in below to provoke a DriveApp authorization dialog if you’re not using DriveApp elsewhere in your app.
Getting a folder by path
This will return a Drive Folder object (or null) for the folder matching the path
Getting a path from a folder
You may need to go the other way – this will generate a full path string from a given folder
Get files from a path
This will return all the files that match a path including a filename. There may be more than one with exactly the same name in the same folder, which is why it will return a file iterator – it’s annoying, but there it is.
Get a single file from a path
This returns the Drive File object that is returned first from a drive files iterator and is most common if you are not worried that there may be multiple files with the same name
Iterators
Now we can start to use V8 iterators, by converting a Drive files or folders iterator into proper V8 iterators.
Get a v8 iterator from a files or folders iterator
Although these examples are all about Drive – any iterator with a hasNext() and a next() will be converted with this function.
Get a v8 iterator for all the files in a folder from a path
Finally, the most useful one – you can use this iterator to get all the file objects in a folder path string
Example usage
Files in a folder iteration
Let’s say you want to iterate through all the files in a folder path
Array from files in a folder path
Or map an array from all the files in a folder path
Array from a folder object
or if you already have a folder object
Get a pile of files
There are a a number of options for this method – see this article for examples and details Getting a pile of files from Google Drive with Apps Script
Links
library: 16NWIRmwJJY_wN4erx_QZA36_ssaB2GiKDPYebj7fjBU1SpVQlo9N_RA7