Search code examples
node.jsgoogle-drive-apigoogle-drive-realtime-api

Downloading progress in Google Drive


In my Meteor server app, I am downloading a file from Google Drive using this code,

var dest = fs.createWriteStream('/data/'+data.name);
        drive.files.get({
           fileId: data.id,
           alt: 'media',
           auth: jwtClient
        })
        .on('end', Meteor.bindEnvironment(function() {

        }))
        .on('error', function(err) {
          console.log('Error during download', err);
        })
        .pipe(dest);

How can I get the progress of the download? For example, i want every 30 seconds to display progress of the download using console.log()

Can I use .on('data')? I am using google drive nodejs v3 provided by Google.


Solution

  • You can get File meta (id, name, size) from drive.files.list with file name, then you can download the file.

    Use Node.js Quickstart for google drive to authenticate.

    I am using progress-stream to measure % data received.

    var callAfterDownload = function (fileName, callback) {
      drive.files.list({
        auth: oauth2Client,
        pageSize: 1,
        q: 'name=\'' + fileName + '\'',
        fields: 'nextPageToken, files(id, name, size)'
      }, function (err, response) {
        if (err) {
          console.log('The API returned an error: ' + err)
          callback(['Error while download'])
        } else {
          var files = response.files
          //when only one file is matched we will download
          if (files.length === 1) {
    
            var file = files.pop()
            console.log('%s (%s)', file.name, file.id)
            var dest = fs.createWriteStream(file.name)
            var progress = Progress({time:100, length: file.size})
    
            //downloading matched file from drive
            drive.files.get({
              auth: oauth2Client,
              fileId: file.id,
              alt: 'media'
            }).on('error', function (err) {
              console.log('Error during download', err)
              callback(['Error while download'])
            }).pipe(progress).pipe(dest)
    
            //checking progress of file
            progress.on('progress', function(progress) {
              console.log('download completed ' +progress.percentage.toFixed(2) + '%')
            });
    
            //when write stream has finally written to file
            dest.on('finish', callback)
    
          } else {
            console.log('EXITING......More than one/no file exist with same name, make sure you have unique file name.')
            callback()
          }
        }
      })
    }
    
    
    function downloadDriveFile () {
      var fileName = 'testfile.doc'
      callAfterDownload(fileName, function (err) {
        if(err) throw err
        //your logic to do anything with the file
      })
    }
    
    downloadDriveFile();