Javascript 使用NodeJS在googledriveapi中获取特定文件的内容

Javascript 使用NodeJS在googledriveapi中获取特定文件的内容,javascript,node.js,promise,google-api-js-client,Javascript,Node.js,Promise,Google Api Js Client,我发现了许多关于如何使用API从google drive检索.txt文件内容的帖子。我试过使用这个: const drive = google.drive({version: 'v3', auth}); var data = drive.files.get({ fileId: file_id, alt: "media" }); data.execute(function(response){ consol

我发现了许多关于如何使用API从google drive检索
.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
还有
数据。然后
而不是
数据。每次我研究并发现没有解决方法的错误时,执行
。有人能告诉我如何从文件id获取文件内容的更新版本吗?因为我认为以前的答案有些过时

如果这很明显,我很抱歉。一般来说,我对javascript和API比较陌生。所以这对我帮助很大,因为这是我完成课程前的最后一段时间:)


谢谢,Mathias当你为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);
有关更多信息,请查看

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

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

你能在问题中加一个错误吗?对不起。我现在添加了它,希望能有所帮助。谢谢没有办法只获取谷歌硬盘文件的数据,而不必先下载它吗?是的,你也可以获取它。让我把它添加到回答中。非常感谢。我相信我会在我的许多节点程序中重用这些代码,这些程序是返回特定文件内容的程序?如果您还没有添加它,那么我的错误上面两个带有fileID的代码为您提供了特定的文件内容,并且没有必要使用writeStream来保存它,您可以控制数据。