Created
March 24, 2021 18:08
-
-
Save hizkifw/79a33dbec462b82cff6646b2b3978b7f to your computer and use it in GitHub Desktop.
Recursively iterate over Google Drive files and folders in Google Apps Script with continuation support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function scanFolder(folder, stopTime, callback) { | |
let ct = null; | |
const properties = PropertiesService.getScriptProperties(); | |
// Iterate files | |
ct = properties.getProperty('iter:' + folder.getId() + ':files') | |
let files = folder.getFiles(); | |
if(ct) files = DriveApp.continueFileIterator(ct); | |
while(files.hasNext()) { | |
const file = files.next(); | |
callback('file', file); | |
if(files.hasNext()) { | |
ct = files.getContinuationToken(); | |
properties.setProperty('iter:' + folder.getId() + ':files', ct); | |
} | |
if(Date.now() > stopTime) return; | |
} | |
// Iterate folders | |
ct = properties.getProperty('iter:' + folder.getId() + ':folders'); | |
let folders = folder.getFolders(); | |
if(ct) folders = DriveApp.continueFolderIterator(ct); | |
while(folders.hasNext()) { | |
const _folder = folders.next(); | |
callback('folder', _folder); | |
scanFolder(_folder, stopTime, callback); | |
if(folders.hasNext()) { | |
ct = folders.getContinuationToken(); | |
properties.setProperty('iter:' + folder.getId() + ':folders', ct) | |
} | |
if(Date.now() > stopTime) return; | |
} | |
} | |
// Sample usage | |
function cb(type, f) { | |
console.log(type, f.getName()) | |
} | |
function test() { | |
scanFolder(DriveApp.getFolderById(''), Date.now() + 300000, cb); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment