Skip to content

Instantly share code, notes, and snippets.

@xergiodf
Last active April 4, 2018 16:20
Show Gist options
  • Select an option

  • Save xergiodf/22576a58bad8e6369c2d54f809707d71 to your computer and use it in GitHub Desktop.

Select an option

Save xergiodf/22576a58bad8e6369c2d54f809707d71 to your computer and use it in GitHub Desktop.
Create a zip file containing folders and files from Google Drive. I was trying to create a zip backup file of all files and folders inside Google Drive, but the result is having all the files converted to PDF (it's the way BLOB works inside Google Apps Scripts)
/**
* Returns an Array of Blobs based on the Folder
* @param reFolder - Google Folder type
* @param path
* @returns {Array}
* @private
*/
function __getBlobsPath(reFolder, path) {
var blobs = [];
var files = reFolder.getFiles();
while (files.hasNext()) {
var file = files.next().getBlob();
file.setName(path + file.getName());
blobs.push(file);
}
var folders = reFolder.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
var fPath = path + folder.getName() + '/';
blobs.push(Utilities.newBlob([]).setName(fPath)); //comment/uncomment this line to skip/include empty folders
blobs = blobs.concat(__getBlobsPath(folder, fPath));
}
return blobs;
}
/**
* Util function that will run with a time-driven trigger.
* It will backup all contract folders and the main spreadsheet
* @private
*/
function __backupFiles() {
var date = Utilities.formatDate(new Date(), "GMT", "dd-MM-yyyy");
var backupFolder = DriveApp.getFolderById(backupFolderId);
var contractFolder = DriveApp.getFolderById(contractsFolderId);
var names = {};
var zip = Utilities.zip(__getBlobsPath(contractFolder, '').map(function (f) {
var n = f.getName();
while (names[n]) {
n = '_' + n
}
names[n] = true;
return f.setName(n);
}), "backup-" + date + ".zip");
backupFolder.createFile(zip);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment