Skip to content

Instantly share code, notes, and snippets.

@NeuroWhAI
Created January 18, 2023 14:14
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 NeuroWhAI/2eaf7e97bfd0bda1ea2fa7b26acc7e85 to your computer and use it in GitHub Desktop.
Save NeuroWhAI/2eaf7e97bfd0bda1ea2fa7b26acc7e85 to your computer and use it in GitHub Desktop.
Google Drive API - List folders and download images inside
import { google } from 'googleapis';
import * as fs from 'fs';
function authGoogleApi() {
let auth = new google.auth.GoogleAuth({
keyFile: './service-account.json',
scopes: [
'https://www.googleapis.com/auth/drive.readonly',
],
});
return auth;
}
const drive = google.drive({ version: 'v3', auth: authGoogleApi() });
const folderId = '{Root Folder ID}';
const res = await drive.files
.get({ fileId: folderId })
.catch((err) => console.log(err.errors));
var query =
"'" +
folderId +
"' in parents and trashed = false";
drive.files.list(
{
q: query,
fields: "files(id, name)",
},
async function (error, response) {
if (error) {
return console.log("ERROR", error);
}
for (var folder of response.data.files) {
const res = await drive.files
.get({ fileId: folder.id })
.catch((err) => console.log(err.errors));
const folderName = res.data.name;
if (!fs.existsSync("./img/" + folderName)) {
fs.mkdirSync("./img/" + folderName);
}
var query =
"'" +
folder.id +
"' in parents and mimeType contains 'image/' and trashed = false";
drive.files.list(
{
q: query,
fields: "files(id, name)",
},
function (error, response) {
if (error) {
return console.log("ERROR", error);
}
response.data.files.forEach(function (item) {
var file = fs.createWriteStream("./img/" + folderName + "/" + item.id + " - " + item.name);
file.on("finish", function () {
console.log("downloaded", item.name);
});
// Download file
drive.files.get(
{
fileId: item.id,
alt: "media",
},
{
responseType: "stream",
},
function (err, response) {
if (err) return "";
response.data
.on("error", (err) => { })
.on("end", () => { })
.pipe(file);
}
);
});
}
);
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment