John Smith John Smith - 5 months ago 184
Javascript Question

Insert File to Drive Folder (check if folder exists, else create folder)

Im trying to insert a specific file in Google Drive to a folder. I also want to check if there is a folder with name 'testFolder' if Yes, then insert file to that already existing folder, else create one named 'testFolder'.

Here is what i have come up with so far. But it always creates a new folder named 'testFolder' so users have like 10 folders named 'testFolder' now. (It dosen't reuse the first folder).

function InsertFileToFolder() {

var file = DriveApp.getFileById(copyId);
var folder;
if (folderExists() == true){

folder = DriveApp.getFolder("testFolder"); //<-- No such thing in GAS i think?
}else{
folder = DriveApp.createFolder("testFolder");
}
folder.addFile(file);
}

function folderExists() { //Check whether folder exists or not

var folders = DriveApp.getFolders();
var flag = false;
for(var i=0; i<folders.length; i++){
if(folders[i].getName() == 'testFolder'){
flag = true;
break;
}
}
return flag;
}

Answer

There is no length property of folders. You need to use hasNext().

Google Documentation - Folder Class

 // Log the name of every folder in the user's Drive.
 var folders = DriveApp.getFolders();
 while (folders.hasNext()) {
   var folder = folders.next();
   Logger.log(folder.getName());
 }

This code returns the folder ID if the folder being looked for is found:

function InsertFileToFolder() {

  var file = DriveApp.getFileById(copyId);      
  var folder,
      folderIdOrFalse;

  folderIdOrFalse = folderExists();

  if (folderIdOrFalse !== false) {                        
    folder = DriveApp.getFolderById(folderIdOrFalse);
  } else {
    folder = DriveApp.createFolder("testFolder");
  };

  folder.addFile(file);
};

function folderExists() { //Check whether folder exists or not

  var folders = DriveApp.getFolders();
  var theReturn = false,
      i=0,
      folderName = "",
      folder;  

  while (folders.hasNext()) {
    folder = folders.next();
    folderName = folder.getName();

    if (folderName === 'testFolder') {
      theReturn = folder.getId();
      break;
    };
  };

  return theReturn;
};