使用 google 驱动器 api 获取文件内容

Get a files contents with google drive api

我想使用 google-api-nodejs-client 获取 google 驱动器文件内容。现在我正在使用下面的代码,只是一个正常的请求,需要 token 才能工作。我正在继续使用 api 做更多的事情,我想使用 oauth2Client 和库来发出这个请求。可能吗?

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

来自 google 的文档:

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);
  }
}