【问题标题】:Get contents of a specific file in google drive API with NodeJS使用 NodeJS 在 google drive API 中获取特定文件的内容
【发布时间】:2021-05-15 11:07:23
【问题描述】:

我发现了很多关于如何使用他们的 API 从谷歌驱动器中检索.txt 文件内容的帖子。我试过用这个:

const drive = google.drive({version: 'v3', auth});
    var data = drive.files.get({
        fileId: file_id,
        alt: "media"
    });
    data.execute(function(response){
        console.log(reponse)
    })

我的错误

data.execute(function(response){
     ^

TypeError: data.execute is not a function

还有data.then,而不是data.execute,每次我研究发现错误并找不到解决方法时。有人可以给我一个如何从文件 id 获取文件内容的更新版本吗?因为我认为以前的答案有些过时了。

对不起,如果这很明显。一般来说,我对 javascript 和 apis 比较陌生。所以这对我有很大帮助,因为这是我完成程序之前的最后阶段:)

谢谢,马蒂亚斯

【问题讨论】:

  • 您能在问题中添加错误吗?
  • 对不起。我现在已经添加了,希望对您有所帮助。谢谢!

标签: javascript node.js promise google-api-js-client


【解决方案1】:

当您为 google drive API 运行“drive.files.get”时,您会收到一个承诺,并获取您必须使用的数据。它是这样工作的:

  const filePath = `give_path_tosave_file`;
  const dest = fs.createWriteStream(filePath);
  let progress = 0;

  drive.files.get(
    { fileId, alt: 'media' },
    { responseType: 'stream' }
  ).then(res => {
    res.data
      .on('end', () => {
        console.log('Done downloading file.');
      })  
      .on('error', err => {
        console.error('Error downloading file.');
      })  
      .on('data', d => {
        d+='';
        console.log(d);
        //data will be here
        // pipe it to write stream
        }   
      })  
      .pipe(dest);
  }); 

如果上述解决方案不起作用,您可以使用此解决方案。它在谷歌官方网站上也可以这样做:

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

更多信息,请查看here

此外,以下方法将返回您在驱动器中可以访问的所有文件。

drive.files.list({}, (err, res) => {
  if (err) throw err;
  const files = res.data.files;
  if (files.length) {
  files.map((file) => {
    console.log(file);
  });
  } else {
    console.log('No files found');
  }
});

【讨论】:

  • 有没有办法只获取google驱动文件的数据,而不必先下载?
  • 是的,你也可以得到它。让我把它添加到答案中
  • 非常感谢。我确信我会在我的许多节点程序中重用这段代码
  • 哪个是返回特定文件内容的?如果您还没有添加它,那么我的错误
  • 当然,你可以检查一下,我还添加了官方的 google 链接,它可以帮助你使用 Node.js 实现这一目标
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 2020-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多