user6570282
user6570282

Reputation:

Add file to an existing folder if file doesn't exist in that folder

So far I have the following code:

function myFunction() {
  var lema = 'house';
  var trad = 'casa';
  var folder = DriveApp.getFolderById('0B_5BQ4yVTu...');
  var doc1 = DriveApp.createFile(lema + ' [ie] ' + trad, '~');
  var doc2 = DriveApp.createFile(trad + ' [ei] ' + lema, '~');
  folder.addFile(doc1);
  folder.addFile(doc2);
}

It creates two files (doc1 and doc2) and moves them to the specified folder, even if the two files already exist.

Please help me to improve this code so it adds the two files only if they don't exist. Is it possible to check if a file exist using only it's name?

Thanks.

Upvotes: 0

Views: 694

Answers (1)

Amit Agarwal
Amit Agarwal

Reputation: 11268

You can create files directly inside the destination folder.

function myFunction() {
  var lema = 'house';
  var trad = 'casa';
  var folder = DriveApp.getFolderById('0B_5BQ4yVTu...');
  var fileName1 = lema + ' [ie] ' + trad;
  if (!folder.getFilesByName(fileName1).hasNext()) {
    folder.createFile(fileName1, '~');
  }
  var fileName2 = lema + ' [ei] ' + trad;
  if (!folder.getFilesByName(fileName2).hasNext()) {
    folder.createFile(fileName2, '~');
  }
}

Upvotes: 1

Related Questions