Reputation: 1052
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?
Upvotes: 2
Views: 12322
Reputation: 22041
This answer might not be relevant to the Author's question but it is relevant for anyone trying to download Gdrive images and who come to this question.
If the images are public, you don't have to use googleapis/google drive sdk to download the images.
The process to download images via the sdk is complex and requires authorization and app creation on Gcloud.
In the case if images are public, they can be download by using the below url:
const imageUrl = `https://drive.google.com/uc?export=download&id=${imageId}`
And below code can be used to download the file, like any other file:
import fs from 'fs';
import request from 'request';
const download = (url, dest, cb) => {
console.log(url);
const file = fs.createWriteStream(dest);
const sendReq = request.get(url);
// verify response code
sendReq.on('response', (response) => {
if (response.statusCode !== 200) {
return cb('Response status was ' + response.statusCode);
}
sendReq.pipe(file);
});
// close() is async, call cb after close completes
file.on('finish', () => file.close(cb));
// check for request errors
sendReq.on('error', (err) => {
fs.unlink(dest, () => cb(err.message)); // delete the (partial) file and then return the error
});
file.on('error', (err) => { // Handle errors
fs.unlink(dest, () => cb(err.message)); // delete the (partial) file and then return the error
});
};
download(imageUrl, 'ImageName');
Upvotes: 1
Reputation: 201378
I believe your goal and situation as follows.
drive.files.get
.For this, how about this answer? In this case, please use responseType
. Ref
In this pattern, the file is downloaded as the stream type and it is saved as a file.
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);
}
);
In this pattern, the file is downloaded as the stream type and it is put to the buffer.
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);
});
}
);
Upvotes: 8