node.jsgoogle-drive-api

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?


Solution

  • I believe your goal and situation as follows.

    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: