@google-cloud/storage version: ^2.5.0I am trying to get file's buffer from google cloud storage, unfortunately there is nothing about buffer in documentation. However I found file api's download return buffer callback according to signatures of download function as follows.
export declare type DownloadCallback = (err: RequestError | null, contents: Buffer) => void;
download(options: DownloadOptions, callback: DownloadCallback): void;
callback supposed to return buffer as contents but it returns undefined and here is my code.
return new Promise((resolve, reject) => {
file.download(
{
destination: key
},
(err, response) => {
if (err) {
reject(err);
}
return resolve(response); // undefined
}
)
});
And here is my workaround which is not efficient.
const file = bucket.file(key);
return rawBody(file.createReadStream());
How can I get a buffer from download function?
If you're only interested in getting a buffer, then you can skip saving the file to your local file system if you omit the destination field in the options passed to File.download():
file.download({
// don't set destination here
}).then((data) => {
const contents = data[0]; // contents is the file as Buffer
});
Hope this answers your question. Please let us know if you are still running into issues.
@jkwlui Thank you, it works.
@jkwlui could you add this code snippet also to the docs? they are not in the examples.
Most helpful comment
If you're only interested in getting a buffer, then you can skip saving the file to your local file system if you omit the
destinationfield in theoptionspassed toFile.download():Hope this answers your question. Please let us know if you are still running into issues.