Reputation: 23
When I run my function in Apps Script its working fine but when I add it in a trigger this error always occurs in first run.
TypeError: folder.getFiles is not a function
This is the code. I use this code to get all files in all folders and subfolders.
var level=0;
function getFnF(folder) {
var folder= folder || DriveApp.getFolderById('root folder ID');
var ss=SpreadsheetApp.openById('google sheet ID');
var sh=ss.getSheetByName('List');
var files=folder.getFiles();
while(files.hasNext()) {
var file=files.next();
var fileid = file.getId();
var TimeStamp = Utilities.formatDate(new Date(), "GMT+8", "MMMM dd, yyyy HH:mm:ss")
var filesize = file.getSize()/ 1024 / 1024;
var lastrow = sh.getLastRow();
var filename =file.getName();
sh.appendRow([TimeStamp,lastrow,filename,file.getName(),filesize.toFixed(2),fileid);
Logger.log('Item added in list: ['+ lastrow+"] " + filename);
}
var subfolders=folder.getFolders()
while(subfolders.hasNext()) {
var subfolder=subfolders.next();
//subfolders only
level++;
getFnF(subfolder);
}
level--;
}
I hope you can help me.
Upvotes: 2
Views: 1987
Reputation: 201398
From When I run my function in apps script its working fine but when I add it in a trigger this error always occurs in first run.
, I'm not sure about the kind of trigger. But when the function is run by a trigger, the event object is given to the 1st argument. So, in this case, how about the following modification?
var level = 0;
function getFnF(e, folder = DriveApp.getFolderById('root folder ID')) {
var ss = SpreadsheetApp.openById('google sheet ID');
var sh = ss.getSheetByName('Sheet1');
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
var fileid = file.getId();
var TimeStamp = Utilities.formatDate(new Date(), "GMT+8", "MMMM dd, yyyy HH:mm:ss")
var filesize = file.getSize() / 1024 / 1024;
var lastrow = sh.getLastRow();
var filename = file.getName();
sh.appendRow([TimeStamp, lastrow, filename, file.getName(), filesize.toFixed(2), fileid]);
Logger.log('Item added in list: [' + lastrow + "] " + filename);
}
var subfolders = folder.getFolders()
while (subfolders.hasNext()) {
var subfolder = subfolders.next();
//subfolders only
level++;
getFnF(e, subfolder);
}
level--;
}
By this modification, when the function getFnF
by a trigger, the function is run as the initial value of folder
of DriveApp.getFolderById('root folder ID')
.
By the way, when you want to run this function from another function instead of the trigger, please call this as getFnF("dummy", folder)
.
Upvotes: 2