从Google驱动程序自行下载xlsx文件

时间:2019-03-26 07:51:46

标签: javascript node.js google-api google-drive-api

因此,我正在尝试制作一个小脚本,通过遵循Google API教程,使用Google Drive API下载一个肯定是excel文件,但我被困在两个错误中:“无法读取未定义的属性'on'”和“请求的转换不受支持” 这是代码:

const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');

const SCOPES = ['https://www.googleapis.com/auth/drive'];
const TOKEN_PATH = 'token.json';
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  authorize(JSON.parse(content), listFiles);
});

/**
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
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]);

  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getAccessToken(oAuth2Client, callback) {
  const authUrl = 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);
      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.
 */
function listFiles(auth) {
  const drive = 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((file) => {
        console.log(`${file.name} (${file.id})`);
      });
    } else {
      console.log('No files found.');
    }
    var fileId = '1lKhyW1O519_1V1QhL9Vkbu55HqyfrgaUbnF4fmhZqU0';
    var dest = fs.createWriteStream('/home/oem/Desktop/TTHIS/report-2019-03-26.xls');
    drive.files.export({
    fileId: fileId,
    mimeType: 'xls'
    })
    .on('end', function () {
      console.log('Done');
    })
    .on('error', function (err) {
      console.log('Error during download', err);
    })
    .pipe(dest);


  });

}

请记住,代码的第一部分仅用于授权,因此真正的问题始于函数listFiles()。 谢谢您的时间!

1 个答案:

答案 0 :(得分:1)

此修改如何?

修改点:

  1. 为了使用response.data,使用{responseType: 'stream'}
    • This thread对于您的情况可能有用。
    • 在线程中,使用files.get方法。但这也可以用于files.export的方法。
  2. 没有xls的mimeType。对于xlsx格式,请使用application/vnd.openxmlformats-officedocument.spreadsheetml.sheet的mimeType。

修改后的脚本:

请进行如下修改。

从:
var fileId = '1lKhyW1O519_1V1QhL9Vkbu55HqyfrgaUbnF4fmhZqU0';
var dest = fs.createWriteStream('/home/oem/Desktop/TTHIS/report-2019-03-26.xls');
drive.files.export({
fileId: fileId,
mimeType: 'xls'
})
.on('end', function () {
  console.log('Done');
})
.on('error', function (err) {
  console.log('Error during download', err);
})
.pipe(dest);
至:
var fileId = '1lKhyW1O519_1V1QhL9Vkbu55HqyfrgaUbnF4fmhZqU0';
var dest = fs.createWriteStream('/home/oem/Desktop/TTHIS/report-2019-03-26.xls');
drive.files.export({
  fileId: fileId,
  mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
}, {responseType: 'stream'}, function(err, response) {
  response.data
    .on('end', function() {
      console.log("Done.");
    })
    .on('error', function(err) {
      console.log('Error during download', err);
      return process.exit();
    })
    .pipe(dest);
});

注意:

  • 如果发生与Drive API相关的错误,请再次确认是否在API控制台上启用了Drive API。
  • 此修改后的脚本假定1lKhyW1O519_1V1QhL9Vkbu55HqyfrgaUbnF4fmhZqU0的文件为Spreadsheet。

在我的环境中,我可以确认此修改后的脚本有效。但是,如果这对您的环境不起作用,我深表歉意。