Home > Software design >  Firebase Storage download in temp folder in cloud functions
Firebase Storage download in temp folder in cloud functions

Time:10-30

I'm trying to download a file from google cloud storage in the temp directory, so then I can unlink the file, but I always receive an empty buffer after the download. The problem present itself if I add the temp path as option in the download method. This is my code:

/**
 * Download the file to a local temp file and returns the buffer and the temp folder path
 * @param {string} filePath
 * @return {array} [buffer, tempFilePath]
 */
async function downloadFile(filePath: string): Promise<[Buffer, string]> {
  const storage = new Storage();
  const bucket = storage.bucket('**********');
  const fileName = path.basename(filePath);
  const tempFilePath = path.join(os.tmpdir(), fileName);
  const [buffer] = await bucket.file(filePath).download({ destination: tempFilePath });
  return [buffer, tempFilePath];
}

If I remove the { destination: tempFilePath } everything work fine. What am I missing? Thank you as always to who will help!

CodePudding user response:

As soon as you provide a destination the file will be saved to disk and no buffer is returned.

This means if you need a buffer and a file you will have to create one of them. You have two ways of doing this. Either keep the code you have right now and then just read the file into a buffer again. Something like this should work:

/**
 * Download the file to a local temp file and returns the buffer and the temp folder path
 * @param {string} filePath
 * @return {array} [buffer, tempFilePath]
 */
async function downloadFile(filePath: string): Promise<[Buffer, string]> {
  const storage = new Storage();
  const bucket = storage.bucket('**********');
  const fileName = path.basename(filePath);
  const tempFilePath = path.join(os.tmpdir(), fileName);
  await bucket.file(filePath).download({ destination: tempFilePath });
  const buffer = await fs.readFile(tempFilePath);
  return [buffer, tempFilePath];
}

or and i think that is the cleaner solution. Don't set the destination, get the buffer and then write this buffer to disk yourself. This would look something like this:

/**
 * Download the file to a local temp file and returns the buffer and the temp folder path
 * @param {string} filePath
 * @return {array} [buffer, tempFilePath]
 */
async function downloadFile(filePath: string): Promise<[Buffer, string]> {
  const storage = new Storage();
  const bucket = storage.bucket('**********');
  const fileName = path.basename(filePath);
  const tempFilePath = path.join(os.tmpdir(), fileName);
  const buffer = await bucket.file(filePath).download();
  await fs.writeFile(tempFilePath, buffer);
  return [buffer, tempFilePath];
}
  • Related