Google drive API downloading file nodejs

孤人 提交于 2020-12-15 03:53:58

问题


Im trying to get the contents of a file using the google drive API v3 in node.js. I read in this documentation I get a stream back from drive.files.get({fileId, alt: 'media'})but that isn't the case. I get a promise back.

https://developers.google.com/drive/api/v3/manage-downloads

Can someone tell me how I can get a stream from that method?


回答1:


I believe your goal and situation as follows.

  • You want to retrieve the steam type from the method of drive.files.get.
  • You want to achieve this using googleapis with Node.js.
  • You have already done the authorization process for using Drive API.

For this, how about this answer? In this case, please use responseType. Ref

Pattern 1:

In this pattern, the file is downloaded as the stream type and it is saved as a file.

Sample script:

var dest = fs.createWriteStream("###");  // Please set the filename of the saved file.
drive.files.get(
  {fileId: id, alt: "media"},
  {responseType: "stream"},
  (err, {data}) => {
    if (err) {
      console.log(err);
      return;
    }
    data
      .on("end", () => console.log("Done."))
      .on("error", (err) => {
        console.log(err);
        return process.exit();
      })
      .pipe(dest);
  }
);

Pattern 2:

In this pattern, the file is downloaded as the stream type and it is put to the buffer.

Sample script:

drive.files.get(
  {fileId: id, alt: "media",},
  {responseType: "stream"},
  (err, { data }) => {
    if (err) {
      console.log(err);
      return;
    }
    let buf = [];
    data.on("data", (e) => buf.push(e));
    data.on("end", () => {
      const buffer = Buffer.concat(buf);
      console.log(buffer);
    });
  }
);

Reference:

  • Google APIs Node.js Client


来源:https://stackoverflow.com/questions/62476413/google-drive-api-downloading-file-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!