简体   繁体   中英

How do I check if a file exists (by name) in Google Drive?

Using Google Apps Script, I'm trying to check if a file exists in Google Drive, given its name ( nomeDB ).

Everywhere except in the trash.

var haBDs = DriveApp.getFilesByName(nomeDB);
  if(!haBDs.next()){
    Logger.log('It does not exist');
  }

Now, DriveApp.getFilesByName returns a FileIterator, which is an object. If the object size is zero, or it doesn't exist, this should solve the problem, right?

Instead of using the .next(), use the .hasNext() function. I think you would run into problems with .next() trying to grab a file that doesnt exist.
Other than that your code looks fine!
I am not 100% sure if the .getFilesByName() method returns an empty FileIterator or null when no files are found, but if you are having issues you could test this by changing your if statement conditions to
(!hasBDs.hasNext() || haBDs == null)

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