Created
January 18, 2023 14:14
-
-
Save NeuroWhAI/2eaf7e97bfd0bda1ea2fa7b26acc7e85 to your computer and use it in GitHub Desktop.
Google Drive API - List folders and download images inside
This file contains 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
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