Reputation: 2972
Here is my code based on Google: "Here are examples of performing a file download with our Drive API client libraries." NODE.JS
const fs = require('fs')
const google = require('googleapis')
const googleAuth = require('google-auth-library')
const SCOPES = ['https://www.googleapis.com/auth/drive'] // Full, permissive scope to access all of a user's files, excluding the Application Data folder. Request this scope only when it is strictly necessary.
const TOKEN_DIR = './credentials/'
const TOKEN_PATH = TOKEN_DIR + 'token4joeDlEs6.json'
const CLIENT_SECRET_FILEPATH = 'client_secret.json'
var clientSecretStr = fs.readFileSync(CLIENT_SECRET_FILEPATH).toString('utf-8')
var tokenStr = fs.readFileSync(TOKEN_PATH).toString('utf-8')
var credentials = JSON.parse(clientSecretStr)
var clientSecret = credentials.installed.client_secret
var clientId = credentials.installed.client_id
var redirectUrl = credentials.installed.redirect_uris[0]
var auth = new googleAuth()
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl)
oauth2Client.credentials = JSON.parse(tokenStr)
var drive = google.drive('v3');
// ["Examples"-NODE.JS tab](https://developers.google.com/drive/v3/web/manage-downloads)
var fileId = 'OBFUSCATED' // Safeway (OBFUSCATED)
var dest = fs.createWriteStream('out/safeway.txt')
drive.files.get({
auth: oauth2Client,
fileId: fileId,
//alt: 'media'
})
.on('end', function () {
console.log('Done');
})
.on('error', function (err) {
console.log('Error during download', err);
})
.pipe(dest);
$ node joeDlSample.js
Done
$
out/safeway.txt to contain my shopping list. :)
out/safeway.txt contains
{
"access_token" : "OBFUSCATED.OBFUSCATED",
"expires_in" : 3600,
"token_type" : "Bearer"
}
I also uploaded a .jpg picture, & uncommented the alt: media
line in the code
out/elb.jpg to contain elb picture
out/elb.jpg contains
{
"access_token" : "OBFUSCATED.OBFUSCATED",
"expires_in" : 3600,
"token_type" : "Bearer"
}
Upvotes: 0
Views: 837
Reputation: 17613
I managed to get Downloading Files in Drive API working by combining the Drive NodeJS Quickstart and the Download Files sample for NodeJS.
From the NodeJS Quickstart there's this line:
authorize(JSON.parse(content), listFiles);
I created my own downloadFile
function to download files instead of listing files and modified the above mentioned line to
authorize(JSON.parse(content), downloadFile);
And here's the downloadFile
function part from the NodeJS sample:
function downloadFile(auth){
var service = google.drive('v3');
var fileId = 'FILE_ID_OF_SHOPPINGLIST_TEXT_FILE';
var dest = fs.createWriteStream('/usr/local/google/home/username/Downloads/shoppinglist.txt');
service.files.get({
auth: auth,
fileId: fileId,
alt: 'media'
})
.on('end', function () {
console.log('Done');
})
.on('error', function (err) {
console.log('Error during download', err);
})
.pipe(dest);
}
The downloaded file in my Downloads folder:
Works for me :)
Upvotes: 3