Created
December 14, 2021 14:08
-
-
Save gengue/8082b04b34a5bfcc128a171b7a12b62e to your computer and use it in GitHub Desktop.
Google Drive API - Upsert file . create or update a file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
const fs = require("fs"); | |
const path = require("path"); | |
const { google } = require("googleapis"); | |
const SCOPES = ["https://www.googleapis.com/auth/drive"]; | |
const KEYFILE_PATH = "config/credentials.json"; | |
const FOLDER_ID = "14DHCIe3CHdWSX_Z3PHPwsow-fVHE9ApG"; | |
const auth = new google.auth.GoogleAuth({ | |
keyFile: KEYFILE_PATH, | |
scopes: SCOPES, | |
}); | |
const driveService = google.drive({ version: "v3", auth }); | |
async function checkIfFileExists(filename) { | |
const response = await driveService.files.list({ | |
pageSize: 1, | |
q: `name = '${filename}'`, | |
}); | |
if (response.data.files && response.data.files.length === 0) return false; | |
return response.data.files[0].id; | |
} | |
exports.upload = async function upload(filenamePath) { | |
const filename = filenamePath.split(path.sep).pop(); | |
const metadata = { | |
name: filename, | |
parents: [FOLDER_ID], | |
}; | |
const media = { | |
mimeType: "text/plain", | |
body: fs.createReadStream(__dirname + filenamePath), | |
}; | |
// upsert | |
const fileId = await checkIfFileExists(filename); | |
let response; | |
if (fileId) { | |
console.log("existing file. Overwriting...", fileId); | |
response = await driveService.files.update({ | |
fileId, | |
media, | |
fields: "id", | |
}); | |
} else { | |
response = await driveService.files.create({ | |
resource: metadata, | |
media, | |
fields: "id", | |
}); | |
} | |
if (response.status !== 200) { | |
console.log(response); | |
throw new Error("Error uploading files to Google Drive"); | |
} | |
console.log("file uploaded", response.data.id); | |
return response.data.id; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment