简体   繁体   中英

Check whether the ID is a file or folder using GAS

I have several IDs, some are file IDs and some are folder IDs

I need a fastest way to find whether the id is of type folder or file.

isFolder(id) must return true or false

function isFolder(id)
{
 return //true if id is a folder, false if thats a file
}

There is the Apps Script method getFolderById()

It should throw

a scripting exception if the folder does not exist or the user does not have permission to access it.

But apparently there is a bug because the method does not throw an exception if you pass to the method the id of a non-folder. Potentially related to this issue.

Consequently, you won't get around querying for the mimeType.

However,comparing the mimeType against "application/vnd.google-apps.folder" is the same like querying either the file is of type folder - after all for Google a folder is just a file type like any other.

  var file = DriveApp.getFileById(id);
  if(file.getMimeType()=="application/vnd.google-apps.folder"){
    return file;
  }

Note:

If desired, you can use the method getFolders to push all folder ids of your Drive into an array and then query either your current file id is contained in the array, but in most cases this won't be faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM