I'm trying to write a google app script which lists all folders and files in my google drive. The code below returns - Exception: Cannot retrieve the next object: iterator has reached the end.
while looping through files. This works on most folders until it fails on the exception. Any ideas on what causes this to bomb out?
function generateFolderTree() {
try {
var parentFolder = DriveApp.getRootFolder();
getChildFolders(parentFolder);
} catch (e) {
Logger.log(e.toString());
}
}
function getChildFolders(parent) {
var childFolders = parent.getFolders();
while (childFolders.hasNext()) {
var childFolder = childFolders.next();
Logger.log("Folder ID: " + childFolder.getId());
Logger.log("Folder: " + childFolder.getName());
var files = childFolder.getFiles();
while (files.hasNext()) {
// Print list of files inside the folder
Logger.log("--> File Name: " + files.next().getName());
Logger.log("--> Owner: " + files.next().getOwner().getEmail());
}
// Recursive call for any sub-folders
getChildFolders(childFolder);
}
}
I think for some reason, calling
next()
twice is like looking for another file. So, if there is only one file in the folder, then the next time you call it, in your case looking for the owner it errors out. You had the right idea in the folder loop, change the file loop to this.