Skip to content

Instantly share code, notes, and snippets.

@mark05e
Created May 29, 2023 20:34
Show Gist options
  • Save mark05e/e036dfdda03b99573560593c861a8bbc to your computer and use it in GitHub Desktop.
Save mark05e/e036dfdda03b99573560593c861a8bbc to your computer and use it in GitHub Desktop.
/**
* Writes fileContents to a file with the given fileName in the specified folder. If a file with the
* same name already exists, it will either overwrite it or append to it, based on the value of the append parameter.
*
* @param {string} fileName - The name of the file to write to.
* @param {string} fileContents - The contents to write to the file.
* @param {string} folderIdOrUrl - The ID or URL of the folder to write the file to.
* @param {boolean} [append=false] - Whether to append the fileContents to an existing file with the same name.
* @returns {string} The ID of the created or modified file.
*/
function writeToFile(fileName, fileContents, folderIdOrUrl, append = false) {
let folder = DriveApp.getFolderById(getIdFromUrl(folderIdOrUrl));
let files = folder.getFilesByName(fileName);
if (isJSON(fileContents)) {
fileContents = JSON.stringify(fileContents,"",1)
}
if (files.hasNext()) {
// If file already exists, overwrite it or append to it with new contents
let file = files.next();
let newContents = fileContents;
if (append) {
let existingContents = file.getBlob().getDataAsString();
if (existingContents) { // && !fileContents.endsWith("\n")
newContents = "\n" + fileContents;
}
file.setContent(existingContents + newContents);
} else {
file.setContent(newContents);
}
return file.getId();
} else {
// If file doesn't exist, create a new file with given contents
let file = folder.createFile(fileName, fileContents);
return file.getId();
}
}
function writeToFile_test() {
let content = "hello world"
let parentFolder = DRIVE_FOLDER_ROOT_URL
let subFolderId = getOrCreateSubfolderId('mySubfolder',parentFolder)
let filename = "hello.txt"
let newFileId = writeToFile(filename,content,subFolderId,true)
console.log({newFileId}) // { newFileId: '1nU082-um9Pv8hUjMAybCY1wXuI-C0R8E' }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment