Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google drive API downloading file nodejs

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?

like image 209
Laurent Dhont Avatar asked Mar 18 '26 19:03

Laurent Dhont


1 Answers

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
like image 93
Tanaike Avatar answered Mar 20 '26 13:03

Tanaike