2022-05-17
[Google Apps Script] How to create a new folder and save file in it when the folder doesn't exist
What we want to do
On Google Apps Script (GAS), we want to save a document special_text into a directory my_docs. However, we don't know whether the direcory my_docs does exist or not.
When
my_docsexsits, we save the file inmy_docs.When
my_docsdoesn't exist, we create a new foldermy_docsthen save the file in it.
script.gs
function save() {
// Generate a file
const doc = DocumentApp.create("special_text");
doc.getBody().setText("here is my specail content!");
const docId = doc.getId();
const targetFolderName = "my_docs";
// Get folders by name
const folderIterator = DriveApp.getRootFolder().getFoldersByName(
targetFolderName
);
let targetFolder;
if (folderIterator.hasNext()) {
// When the folder exists
targetFolder = folderIterator.next();
} else {
// When the folder doesn't exist
targetFolder = DriveApp.getRootFolder().createFolder(targetFolderName);
}
// Move file into the directory
docFile = DriveApp.getFileById(docId);
targetFolder.addFile(docFile);
}
Key points
We use a function getFoldersByName() to get folder(s) that has specific name.
This function returns FolderIterator class and we can check the folder does exist or not by calling FolderIterator.hasNext() method. This method returns true when the folder exists and returns false when it doesn't exist.
When hasNext() returns true, you can access the folder by FolderIterator.next() method.
When the folder doesn't exist, we will create a folder by createFolder() function.