jeudi 6 février 2020

File list returns undefined when there are no files

I'm using this code to return a list of files in a google drive folder. It works really well, up until there is a folder with no files in it. It returns an error that says "Cannot read property 'length' from undefined".

I'm assuming there needs to be a if, else statement in there somewhere, to return "null" or an acceptable exit to the loop besides "undefined", that can be output to the same range listed in the output.

function kuehnertdates() {
  var folderId = 'FolderID';
  var folder = DriveApp.getFolderById(folderId);
  var files = folder.getFiles();
  var output = []; 
  while (files.hasNext()) {
    var file = files.next();
    output.push([file.getName(), file.getLastUpdated()]);
  }
  output.sort(function(a, b) {
    return a[0] == b[0] ? 0 : a[0] < b[0] ? -1 : 1;
  });
  SpreadsheetApp.getActive().getSheetByName('Farms').getRange(2, 17, output.length, output[0].length).setValues(output);

}

Aucun commentaire:

Enregistrer un commentaire