Search code examples
javascriptnode.jsexpressgoogle-apidrive

NodeJS - Downloading media from Google Drive


I am trying to download one idFile from google drive using googleapis library. However I am encountering the following error:

Cannot read property 'data' of undefined

Here is my code:

const express = require("express");
const path = require ("path");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
const port = 2000
// Google getting started section
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');

app.use(express.static(path.join(__dirname, 'public')));


app.listen(port, () => {
    // Load client secrets from a local file.
    fs.readFile('credentials.json', (err, content) => {
        if (err) return console.log('Error loading client secret file:', err);
        // Authorize a client with credentials, then call the Google Drive API.
        authorize(JSON.parse(content), listFiles, downloadFile);
    });
  
    console.log(`Example app listening at http://localhost:${port}`)
})


// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive.readonly',
                               'https://www.googleapis.com/auth/drive.metadata.readonly',
                            "https://www.googleapis.com/auth/drive.file"];
// 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 = 'token.json';


/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
async function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  await fs.readFile(TOKEN_PATH, async (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    await callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
async function getAccessToken(oAuth2Client, callback) {
  const authUrl = await oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Lists the names and IDs of up to 10 files.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
 async function listFiles(auth) {
  const drive = await google.drive({version: 'v3', auth});

  drive.files.list({
    pageSize: 10,
    fields: 'nextPageToken, files(id, name)',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const files = res.data.files;
    if (files.length) {

      console.log('Files:');
      files.map(async (file) => {
        await downloadFile(auth);
      });
    } else {
      console.log('No files found.');
    }
  });
}

// download to local file  
async function downloadFile(auth) {
    const drive = google.drive({version: "v3", auth});
 var fileId = "1l-2thXStT2W57Ovo9IUI5ki1zP7afCZ6"

 var dest = await fs.createWriteStream("/public/images/photo.jpg");

 drive.files.get(
     {fileId: fileId, alt: "media"}, 
     {responseType: "stream"},
    async function(err, res) {
        res.data
        .on("end", () => {

        })
        .on("error", err => {
        console.log("Error", err);
        })
        .pipe(dest);

    // I am geeting success but I cant find the Image
        console.log("success");
    });
}

I wrote it using the following resources:

Get images from google drive API

https://medium.com/@humadvii/downloading-files-from-google-drive-using-node-js-3704c142a5f6

Google drive API downloading file nodejs

But the error I get is this one:

(node:13788) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'data' of undefined at C:\info\nodejs\server spectrum\main.js:123:13 at processTicksAndRejections (internal/process/task_queues.js:95:5) (Use node --trace-warnings ... to show where the warning was created) (node:13788) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2) (node:13788) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. Blockquote

Pointing to the following line of code:

res.data
    .on("end", () => {

    })
    .on("error", err => {
    console.log("Error", err);
    })
    .pipe(dest);

Do you have any idea how can I solve this one? Thank you very much!!


Solution

  • This is directly from the documentation

    Download

    var fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M';
    var dest = fs.createWriteStream('/tmp/photo.jpg');
    drive.files.get({
      fileId: fileId,
      alt: 'media'
    })
        .on('end', function () {
          console.log('Done');
        })
        .on('error', function (err) {
          console.log('Error during download', err);
        })
        .pipe(dest);