0

I know a folder actually is a file with a special mimeType application/vnd.google-apps.folder in Google Drive. But documentation about DriveApp Folder class doesn't contain a method getMimeType() like DriveApp File class does.

How can find out in a function if an argument of that function refers to a folder or to a (normal) file?

function displayResults(fileOrFolder)
{
  var id   = fileOrFolder.getId();
  var name =  fileOrFolder.getName();

  var mimeType = fileOrFolder.getMimeType();  // works if file; error if folder

  if (fileOrFolder == <Class File>)
  {
     <do something>
  }
  else if (fileOrFolder == <Class Folder>)
  {
     <do something else>
  }
}
SoftwareTester
  • 1,048
  • 1
  • 10
  • 25

3 Answers3

2

Look if the method exists. If obj.getMimeType===undefined its a folder.
or, to make it more robust in case the api changes (adds the method to folders), use
if (obj.getMimeType===undefined || obj.getMimeType.toLowerCase() =="application/vnd.google-apps.folder")

Zig Mandel
  • 19,571
  • 5
  • 26
  • 36
0

I don't understand why you say that Zig's answer does not work... All the tests I made were positive.

example of how I tested it (test ID are shared publicly and so should work for anybody):

function test(){
  var item = DriveApp.getFileById('0B3qSFd3iikE3MS0yMzU4YjQ4NC04NjQxLTQyYmEtYTExNC1lMWVhNTZiMjlhMmI');
  testDriveFolders(item);
  var item = DriveApp.getFileById('1fXxLHuDlySZ6rOQjTsZdUl6rnw14sa17Q0ZTZ0HoGk1jbuHX-eLq1dyf');
  testDriveFolders(item);
}

function testDriveFolders(obj){
  try{var mimeType = obj.getMimeType()}catch(e){mimeType = 'folder'};
  var name =  obj.getName();
  if (mimeType =="application/vnd.google-apps.folder" || mimeType == 'folder'){
    Logger.log(name+' is a folder');
  }else{
        Logger.log(name+' is of the type '+mimeType);
  }
}
Serge insas
  • 45,904
  • 7
  • 105
  • 131
  • No need for try/catch. In the code i provided i do Not call getMymeType(), i do obj.getMimeType===undefined which is very different. Is checking for existance of the function, not calling it (until later) – Zig Mandel Jun 27 '14 at 13:12
  • Yes indeed, I used it making a mix of the other post and yours because I started by testing his code (that was said "not working"). In the end both methods seems useable... – Serge insas Jun 27 '14 at 14:26
  • 1
    yes sorry I wasnt complaining about this approach, just pointing out why hes try at it wasnt working. try/catch in general is not the best idea because methods could throw genuine error exceptions and not just language exceptions about the method not existing. – Zig Mandel Jun 27 '14 at 14:31
0

Get the file object associated to the ID. getMimeType() will work:

var mt = DriveApp.getFileByID(fileOrFolder.getId()).getMimeType();
if (mt == MimeType.FOLDER) {
  // it's a folder
} else {
  // it's a file.
}
Rafael
  • 11
  • 3