title: Google Script test for file existance
body: <p>I can't believe there isn't a simple way to do this, but I've trawled everywhere for a working solution without success.</p>
  
  <p>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).</p>
  
  <p>The code below that I'm using to test returns "File Exists" regardless of whether the folder or the file exists or not.</p>
  
  <p>As always, any help much appreciated:-)</p>
  
  <p>Here's my test code.</p>
  
  <pre><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};
  }
  </code></pre>
  
  <p>Cheers
  ...Steve</p>