Search code examples
javascriptnode.jsgoogle-api-nodejs-client

Get a files contents with google drive api


I would like to use the google-api-nodejs-client to get a google drive files contents. Right now I'm using the code below, just a normal request, which needs the token to work. I'm moving on to do more things with the api and I wanna use oauth2Client and the library to make this request. Is it possible?

var Promise = require("bluebird")
var request = Promise.promisify(require("request"))

function getDriveFile(token, fileId){
  return request({
    "method":"GET",
    "url": "https://docs.google.com/feeds/download/spreadsheets/Export",
    "qs":{
        "exportFormat": "csv",
        "key": fileId,
        "gid": 0
    },
    "headers":{
        "Authorization": "Bearer " + token
    }
  }).spread(function(response, body){
    return body
  })
}

module.exports = getDriveFile

Solution

  • From google's docs :

    https://developers.google.com/drive/v2/reference/files/get#examples

    /**
     * Print a file's metadata.
     *
     * @param {String} fileId ID of the file to print metadata for.
     */
    function printFile(fileId) {
      var request = gapi.client.drive.files.get({
        'fileId': fileId
      });
      request.execute(function(resp) {
        console.log('Title: ' + resp.title);
        console.log('Description: ' + resp.description);
        console.log('MIME type: ' + resp.mimeType);
      });
    }
    
    /**
     * Download a file's content.
     *
     * @param {File} file Drive File instance.
     * @param {Function} callback Function to call when the request is complete.
     */
    function downloadFile(file, callback) {
      if (file.downloadUrl) {
        var accessToken = gapi.auth.getToken().access_token;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', file.downloadUrl);
        xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
        xhr.onload = function() {
          callback(xhr.responseText);
        };
        xhr.onerror = function() {
          callback(null);
        };
        xhr.send();
      } else {
        callback(null);
      }
    }