Skip to content

Instantly share code, notes, and snippets.

@gengue
Created December 14, 2021 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gengue/8082b04b34a5bfcc128a171b7a12b62e to your computer and use it in GitHub Desktop.
Save gengue/8082b04b34a5bfcc128a171b7a12b62e to your computer and use it in GitHub Desktop.
Google Drive API - Upsert file . create or update a file
"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