Skip to content

Instantly share code, notes, and snippets.

@LindaLawton
Created November 21, 2022 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save LindaLawton/76bef3ab760f335d43eccaf481e0b4d0 to your computer and use it in GitHub Desktop.
Save LindaLawton/76bef3ab760f335d43eccaf481e0b4d0 to your computer and use it in GitHub Desktop.
Example for downloading a file from google drive api using Node.js
// npm install googleapis@105 @google-cloud/local-auth@2.1.0 --save
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'];
// File id of the file to download
const FILEID = 'SetFileIdHere';
// 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:\\Development\\FreeLance\\GoogleSamples\\Credentials\\CredWebEverything.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;
}
/**
* Download file
* @param {OAuth2Client} authClient An authorized OAuth2 client.
*/
async function downloadFile(authClient) {
const service = google.drive({version: 'v3', auth: authClient});
fileId = FILEID;
try {
// get the file name
const fileMetaData = await service.files.get({
fileId: fileId, fields: 'name'
},
);
// create stream writer with the file name from drive
const fileStream = fs.createWriteStream(fileMetaData.data.name)
console.log('downloading: ' + fileMetaData.data.name);
const file = await service.files.get({
fileId: fileId,
alt: 'media',
}, {
responseType: "stream"
}
);
file.data.on('end', () => console.log('onCompleted'))
file.data.pipe(fileStream);
} catch (err) {
// TODO(developer) - Handle error
throw err;
}
}
authorize().then(downloadFile).catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment