Created
May 3, 2024 05:21
-
-
Save willdave865/724d434d40ca9cc126533fff847d7d4c to your computer and use it in GitHub Desktop.
// Test file that aquires authorization then exports a list of gdoc files as text from My Drive to local directory
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
// Test file that aquires authorization then exports a list of gdoc files as text from My Drive to local directory | |
const fs = require('fs'); | |
const fsp = fs.promises; | |
const path = require('path'); | |
const process = require('process'); | |
const {authenticate} = require('@google-cloud/local-auth'); | |
const {google} = require('googleapis'); | |
// If modifying these scopes, delete token.json. | |
const SCOPES = ['https://www.googleapis.com/auth/drive']; | |
// The file token.json stores the user's access and refresh tokens, and is | |
// created automatically when the authorization flow completes for the first | |
// time. | |
const TOKEN_PATH = path.join(process.cwd(), 'DownloadFileToken.json'); | |
const CREDENTIALS_PATH = 'C:\\googleDriveDev\\credentials.json'; | |
/** | |
* Reads previously authorized credentials from the save file. | |
* | |
* @return {Promise<OAuth2Client|null>} | |
*/ | |
async function loadSavedCredentialsIfExist() { | |
try { | |
const content = await fsp.readFile(TOKEN_PATH); | |
const credentials = JSON.parse(content); | |
return google.auth.fromJSON(credentials); | |
} catch (err) { | |
return null; | |
} | |
} | |
/** | |
* Serializes credentials to a file compatible with GoogleAUth.fromJSON. | |
* | |
* @param {OAuth2Client} client | |
* @return {Promise<void>} | |
*/ | |
async function saveCredentials(client) { | |
const content = await fsp.readFile(CREDENTIALS_PATH); | |
const keys = JSON.parse(content); | |
const key = keys.installed || keys.web; | |
const payload = JSON.stringify({ | |
type: 'authorized_user', | |
client_id: key.client_id, | |
client_secret: key.client_secret, | |
refresh_token: client.credentials.refresh_token, | |
}); | |
await fsp.writeFile(TOKEN_PATH, payload); | |
} | |
/** | |
* Load or request or authorization to call APIs. | |
* | |
*/ | |
async function authorize() { | |
let client = await loadSavedCredentialsIfExist(); | |
if (client) { | |
return client; | |
} | |
client = await authenticate({ | |
scopes: SCOPES, | |
keyfilePath: CREDENTIALS_PATH, | |
}); | |
if (client.credentials) { | |
await saveCredentials(client); | |
} | |
return client; | |
} | |
// Code that lists then exports files | |
async function listFilesAndExport(auth) { | |
const drive = google.drive({ version: 'v3', auth }); | |
try { | |
const res = await drive.files.list({ | |
corpora: 'user', | |
pageSize: 100, | |
q: `'11Sejh6XG-2WzycpcC-MaEmDQJc78LCFg' in parents and trashed=false`, | |
fields: 'files(id, name)', | |
}); | |
const files = res.data.files; | |
if (files.length) { | |
const fileIdentity = files.map(file => [file.id, file.name]); | |
return fileIdentity; | |
} else { | |
console.log('No files found.'); | |
return []; | |
} | |
} catch (err) { | |
console.error('The API returned an error:', err); | |
throw err; | |
} | |
} | |
async function exportTxtForFiles(auth) { | |
try { | |
const fileIdentity = await listFilesAndExport(auth); | |
if (fileIdentity.length) { | |
const service = google.drive({ version: 'v3', auth }); | |
for (const [fileId, fileName] of fileIdentity) { | |
const result = await service.files.export({ | |
fileId: fileId, | |
mimeType: 'text/plain', | |
}, { responseType: 'stream' }); | |
const destFile = fs.createWriteStream(`C:\\erctest\\erctest3\\${fileName}.txt`); | |
result.data | |
.on('end', function () { | |
console.log(`File "${fileName}" exported successfully.`); | |
}) | |
.on('error', function (err) { | |
console.error(err); | |
throw err; | |
}) | |
.pipe(destFile); | |
} | |
} else { | |
console.log('No files to export.'); | |
} | |
} catch (err) { | |
console.error('Error exporting files:', err); | |
throw err; | |
} | |
} | |
authorize() | |
.then(exportTxtForFiles) | |
.catch(console.error); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment