使用node.js中的googleapi从Google驱动器导出文件

时间:2018-03-23 10:11:13

标签: node.js google-api

我正在使用googleapi从google驱动器导出文件。我的export.js中有以下代码。当我运行这个文件时,即使我已经给出了mimeType,它也会抛出一个错误,说" API返回错误:错误:必需参数:mimeType"

var drive = google.drive({
  version: 'v3',
  auth: auth
});

var dest = fs.createWriteStream('./public/data/myfile.txt');
drive.files.export({
  fileId : fileID,
  mimeType : 'text/plain'
}, function(err, response) {
  if (err) {
  console.log('The API returned an error: ' + err);
  return;
  }
  console.log('Received %d bytes', response.length);
  fs.writeFileSync(dest, response);
});

2 个答案:

答案 0 :(得分:2)

Ohai!维护者在这里。当发生类似这样的事情时,通常是因为googleapisgoogle-auth-library的版本之间存在一些不匹配。就代码而言,我们在这里有一份完整的工作副本:

https://github.com/google/google-api-nodejs-client/blob/master/samples/drive/export.js

现在 - 做什么。您需要确保a。)您使用的是最新版本的googleapis,并且b。)您的package.json中没有google-auth-library。请尝试:

$ npm uninstall --save google-auth-library $ npm install --save googleapis@28

试一试,让我知道它是怎么回事:)

答案 1 :(得分:0)

我认为您可以通过这种方式进行尝试,并确保您的文件与您请求的mimeType相匹配,也许您需要说您正在接受二进制数据。

drive.files.export({
   fileId: 'asxKJod9s79', // A Google Doc pdf
   mimeType: 'application/pdf'},
   { encoding: null }, // Make sure we get the binary data
   function (err, buffer) {
       // ...
       // convert and write the file
    });

请注意,API会返回一个缓冲区对象,您需要将其转换并写入文件。 Refer this.

或者你可以使用它:

var fileId = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo';
var dest = fs.createWriteStream('/tmp/resume.pdf');
drive.files.export({
  fileId: fileId,
  mimeType: 'application/pdf'
})
    .on('end', function () {
      console.log('Done');
    })
    .on('error', function (err) {
      console.log('Error during download', err);
    })
    .pipe(dest);