Nodejs-storage: Can't get buffer from File's download callback

Created on 25 Apr 2019  路  3Comments  路  Source: googleapis/nodejs-storage

Environment details

  • OS: macOS
  • Node.js version: 8.10.0
  • npm version: 5.6.0
  • @google-cloud/storage version: ^2.5.0

I 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?

storage question

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 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.

All 3 comments

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.

Was this page helpful?
0 / 5 - 0 ratings