Modify Google App Script - Gmail to Google Drive

Viewed 200

I'm trying to modify this script found here: https://github.com/ahochsteger/gmail2gdrive

I need the script to check if the file already exists on Google Drive and if not, create it. Currently, the script just creates the file into Google Drive, without checking to see if an existing file with the same name already exists or not.

I'm not a programmer, I know nothing about Google App Script (although I have managed to set it up and got it running) and I know nothing about JavaScript. I'm just wondering if someone could either point me in the right direction or help me code this one feature that I need?

From what I understand (I could be wrong), the attachment is created based on this line in the code:

var file = folder.createFile(attachment);

So then I tried add this before the createFile:

var file = folder.removeFile(attachment);

My logic here is that if the file exists in the folder, then remove it first before creating it (therefore avoiding duplicate files). But that didn't work.

1 Answers

From the script of GitHub in your question, it is found that attachment is blob. So how about using this filename? I think that there are several solutions for your situation. So please think of this as one of them. The flow of sample script is as follows.

  1. Retrieve the filename of blob.
  2. Retrieve FileIterator using getFilesByName().
  3. If the FileIterator has values, it means that the file with the same filename has already been existing.
  4. If the FileIterator has no values, it means that the file with the same filename is not existing.

The sample script is as follows.

Sample script 1:

If you want to create new file only when the file of same filename is not existing, you can use the following script.

var fileName = attachment.getName();
var f = folder.getFilesByName(fileName);
var file = f.hasNext() ? f.next() : folder.createFile(attachment);

Sample script 2:

If you want to do something when the file of same filename is existing, you can use the following script.

var fileName = attachment.getName();
var f = folder.getFilesByName(fileName);
var file;
if (f.hasNext()) {
  // If the file has already been existing, you can do something here.
} else {
  //  If the file is not existing, you can do something here.
  file = folder.createFile(attachment);
}

Note:

  • From your question, the file is searched from the folder. If you want to search the file from all files, please tell me.

References:

If this was not what you want, please tell me. I would like to modify it.

Related