如何检查 DriveApp.getFolderById() returns 文件夹?

How to check if DriveApp.getFolderById() returns a folder?

当我使用 DriveApp.getFolderById(someId) 其中 someId 属于文件而不是文件夹时,方法 returns 文件而不是出错。如何确保返回的对象确实是一个文件夹?

现在,我能想到的唯一解决方案是 try/catch:

try {
  const testFile = someFile.makeCopy('test', folder);
  testFile.setTrashed(true);
} catch (err) {
  return 'The folder is not really a folder';  
}

是否有更清洁的解决方案?

例如,在您的情况下,如何检查 mimeType 如下?

示例脚本:

const id = "###"; // Please set the file ID and folder ID.

const file = DriveApp.getFileById(id);
if (file.getMimeType() == MimeType.FOLDER) {
  console.log(`This ID (${id}) is a folder.`);
  const folder = DriveApp.getFolderById(id);

  // Do something.

} else {
  console.log(`This ID (${id}) is not a folder.`);
}
  • 当此脚本为运行时,通过检查id的mimeType,可以看出ID是否为文件夹。

参考:

已添加:

根据您的以下回复,

A folder doesn't have a getMimeType function to call, so I guess a check like if (!folder.getMimeType) that a returns true indicates that it's a folder.

如果您想使用 const folder = DriveApp.getFolderById(id) 进行检查,下面的示例脚本怎么样?

示例脚本:

const id = "###"; // Please set the file ID and folder ID.

const folder = DriveApp.getFolderById(id);
if (folder.getUrl().split("/")[4] == "folders") {
  console.log(`This ID (${id}) is a folder.`);

  // In this case, you can directly use the variable of "folder".
  // Do something.

} else {
  console.log(`This ID (${id}) is not a folder.`);
}
  • 在这个示例脚本中,通过检查对象的URL,检查id是否是文件夹。例如,当 id 是 Spreadsheet 时,检索到的 URL 就像 https://docs.google.com/spreadsheets/d/###/edit?usp=drivesdk。本脚本就是利用了这种情况。