Google Script test for file existance

2019-07-31 08:48发布

问题:

I can't believe there isn't a simple way to do this, but I've trawled everywhere for a working solution without success.

I am running a Google script in a Google Sheet and I'm at a point in the code where I want to save the spreadsheet as a new filename. Before I do that I want to check that there isn't already one in existence (because I don't want to overwrite it).

The code below that I'm using to test returns "File Exists" regardless of whether the folder or the file exists or not.

As always, any help much appreciated:-)

Here's my test code.

function testscriptforfileexistance() {
  filecheck = checkfileexists("UnderDevelopment",'20160919 Weekly Roster v1.0.gsheet');

  if (filecheck.filefound = true)  {
    Browser.msgBox("file found") ;
  } else {
    Browser.msgBox("File not found");
  }
}


function checkfileexists(foldername,fn) {
  var destFolder = DriveApp.getFoldersByName(foldername);
  filefound=false;
  var destFileId = DriveApp.getFilesByName(fn);
//if hasnext returns false, presumably it doesn't exist
  if (!destFileId.hasNext) {
    Logger.log ("Found");
    filefound = true;
// and as a second test, if the length is zero the file doesn't exist
  if (!destFileId[0]) {
    Logger.log ("zero length");
    filefound=false;
  }
  }
  return {filefound:filefound};
}

Cheers ...Steve

回答1:

This is a little bit confusing because there is a lot of hasNext involved if you are checking the existence of Folder/File or file in specific folder. I got this working thru trial and error.

hasNext()

  • Determines whether calling next() will return an item.

Return

  • Booleantrue if next() will return an item; false if not

First here are some related SO question :

  • How do I check if a file exists (by name) in Google Drive?
  • Google Apps Script: Check upload file exist or empty

Here is a sample code:

function checkFile(filename){
  var results;
  var haBDs  = DriveApp.getFilesByName(filename)
  //Does not exist
  if(!haBDs.hasNext()){
  results =  haBDs.hasNext();
  }
  //Does exist
  else{
  results =  haBDs.hasNext();
  }
  Logger.log(results)
  return results;
}

function myFunction() {
  var nomeDB = "FILE_NAME";  
  if(checkFile(nomeDB) == true){
  Logger.log("File Found")
  }else{
  Logger.log("File Not Found")
  }

}

Checking your code, try changing !destFileId.hasNext to !destFileId.hasNext()

Additional information, if you will be checking if the file exist in a specific folder you will use the same flow but you will have to check if the folder too does exists (optional).

Here is a snippet for that:

function checkFile2(filename,foldername){

  var folder = DriveApp.getFoldersByName(foldername);

  Logger.log(folder.hasNext());

  //Folder does not exist
  if(!folder.hasNext()){

  Logger.log("No Folder Found");

  }
  //Folder does exist
  else{
    Logger.log("Folder Found")
    var file   = folder.next().getFilesByName(filename);
    if(!file.hasNext()){
       Logger.log("No File Found");
    }
    else{
       Logger.log("File Found");
    }
  }

}

Hope this helps!



回答2:

I found this question looking for a way to see if a file exists in a certain folder.

This is working for me. Checks if a file exists in a given folder by folder Id. I've confirmed that it returns false if there is no file with that name or if the matching file(s) aren't in the given folder. And returns true if the file does exist in the given folder.

function fileExists(name, folderId) {
  var files = DriveApp.getFilesByName(name);
  while (files.hasNext()) {
    var file = files.next();
    var folders = file.getParents();
    if (folders.hasNext()) {
      var folder = folders.next();
      if (folder.getId() == folderId) {
        return true;
      }
    }
  }
  return false;
}


回答3:

If you have more than 1 file in your DropBox, it might always come back True with hasNext? Try testing it with getDateCreated? If it's null, you know it doesn't exist. You could then choose that as your False.



回答4:

Thanks @Mr Rebot (or @Mr-Rebot). Your checkfile2 code nearly worked.

I swapped over foldername and filename in your function call (just for compatibility with the rest of my calling code).

My test calling code now looks like this

function testscriptforfileexistance() {
  if (checkFile2('UnderDevelopment','test.txt')) {
    Browser.msgBox("file found") ;
  } else {
    Browser.msgBox("File not found");
  }
}

With this, my MsgBox message always comes up “File Not Found” even if the file test.txt actually exists, although the log correctly shows [True, Folder Found, File Found]. So I'm assuming the boolean status wasn't being passed back to the calling function.

So I added a bit of explicit Boolean variable stuff and that fixed it, except I then found it only works for filenames without spaces (like ‘test.txt’).

Here’s the modified code that works with a filename search of 'test.txt' but always returns File Not Found and Log entries of [True, Folder Found, No File Found, false] with ‘20160919 Weekly Roster v1.0.gsheet’

    function testscriptforfileexistance() {
  check= checkFile2("UnderDevelopment","20160919 Weekly Roster v1.0.gsheet");
  if (check.filefound==true) {
    Browser.msgBox("file found") ;
  } else {
    Browser.msgBox("File not found");
  }
}

function checkFile2(foldername,filename){
    //Supplied version Mr Rebot -  testing
      var filefound=false;
      var folder = DriveApp.getFoldersByName(foldername);

  Logger.log(folder.hasNext());

  //Folder does not exist
  if(!folder.hasNext()){

  Logger.log("No Folder Found");

  }
  //Folder does exist
  else{
    Logger.log("Folder Found")
    var file   = folder.next().getFilesByName(filename);
    if(!file.hasNext()){
       Logger.log("No File Found");
    }
    else{
       Logger.log("File Found");
       filefound=true;
    }
  }
  Logger.log(filefound);
  return {filefound:filefound};
}

I tried putting the parameters on the call to checklist2 in double quotes instead of single quotes but that made no difference.

Still don’t know why this is so hard in GAS – checking whether a file exists must be something done frequently I would have thought.

Appreciate any help Mr Rebot (and Tulio!):-)

Cheers ...Steve