Google Apps Script ➡️ Utils. Get or find a folder by name and create a new if not exist

Max Makhrov
3 min readSep 6, 2023

The code here is the part of “Utils” project on GitHub.

A piece of code that showcases a functionality to locate, access, and potentially create a folder within Google Drive using Google Apps Script:

/**
* @typedef {Object} OptionsGetFolder
* @property {String} [root_folder_id]
* @property {String} [folder_name]
* @property {String} [folder_id]
* @property {Boolean} [create_if_not_found]
* @property {Boolean} [do_not_throw_error]
*/

/**
* @param {OptionsGetFolder} options
* @returns {DriveApp.Folder}
*/
function getFolder_(options) {
options = options || {};

var badEnd_ = function(msg) {
msg = '😖' + msg;
if (options.do_not_throw_error) {
console.log(msg);
return null;
}
throw msg;
}

var folder;
if (options.folder_id) {
try {
folder = DriveApp.getFolderById(options.folder_id);
} catch (err) {
return badEnd_('could not find folder or you do not have access to: ' + options.folder_id);
}
return folder;
}

if (!options.folder_name) {
return badEnd_('required field is missing: `folder_id` OR `folder_name`.')
}

var root;
if (options.root_folder_id) {
try {
root = DriveApp.getFolderById(options.root_folder_id);
} catch(err) {
return badEnd_('could not find root folder or you do not have access to: ' + options.root_folder_id);
}
} else {
root = DriveApp.getRootFolder();
}

var folders = root.getFolders();
var subFolder;
while (folders.hasNext()) {
subFolder = folders.next();
if (subFolder.getName() === options.folder_name) {
return subFolder;
}
}

if (options.create_if_not_found) {
folder = root.createFolder(options.folder_name);
return folder;
}

return badEnd_('could not find folder "' + options.folder_name + '" in folder "' + root.getName() + '"');
}

Test:

function test_getFolder() {
// good tests
console.log(getFolder_({folder_id: 'FOLDER_ID'}).getName())
console.log(getFolder_({folder_name: 'FOLDER_NAME', root_folder_id: 'FOLDER_ID'}).getName());
console.log(getFolder_({root_folder_id: 'FOLDER_ID', folder_name: 'Test', create_if_not_found: true}).getName())

// bad tests
console.log(getFolder_({root_folder_id: 'foo', folder_name: 'My Folder', do_not_throw_error: true}).getName())
console.log(getFolder_({root_folder_id: 'foo', folder_name: 'My Folder'}).getName())
console.log(getFolder_({root_folder_id: 'foo'}).getName())
console.log(getFolder_({folder_id: 'foo'}).getName())
console.log(getFolder_({folder_name: 'foo', root_folder_id: 'FOLDER_ID'}).getName());
}

The sample usage of this code is if you need to create new folders inside other folders, but do not want to create 2 folders with the same name.

The given JavaScript code defines a function named `getFolder_`. This function is designed to handle a variety of tasks related to file management. By accepting an options object as a parameter, the function can be tailored to suit different needs, validating its flexibility for various business use cases.

The accepted options consist of properties such as `root_folder_id`, `folder_name`, `folder_id`, `create_if_not_found`, and `do_not_throw_error`. It is worth noting that all these properties are optional, ensuring that the function can operate in different contexts with varying levels of information.

Photo by Marco Bianchetti on Unsplash

Options

If the option `folder_id` is provided, the function attempts to fetch the corresponding folder, throwing an error if it fails. If `folder_id` is absent but `folder_name` is given, the function scans through the folders present in the defined root or default root folder till it locates a folder with the matching name.

The `root_folder_id` property lets the user specify a specific root folder they wish to search within. If left undefined or if the specified root is inaccessible, the function defaults to the Drive’s root folder.

The `create_if_not_found` property, if set as true, allows the function to create a new folder with the given `folder_name` in case it cannot find an existing folder with the same name. This feature could be particularly useful in scenarios where dynamic folder creation is required, such as in data segregation or categorizing documents.

Lastly, the `do_not_throw_error` option provides an ability to suppress any error thrown by the function, instead of logging the error message to the console. This feature can be useful in instances where the function operation is not critical to the flow of the software, preventing hiccups due to unnecessary termination of the code execution.

Use cases

In a business context, the `getFolder_` function can be really empowering. Whether it’s about automating file organization, establishing a well-structured data system in Google Drive, or error management while dealing with file manipulation, this function encapsulates enough flexibility to cater to different requirements and use cases. By handling the core aspect of folder operations in Drive, businesses can utilize this function as a stepping stone to build more complex, tailor-made solutions that fit their specific needs.

--

--

Max Makhrov

Google Sheets Developer, master of Online Accounting