jurifo
jurifo

Reputation: 11

How can I download file inside a folder in Google Cloud Storage using Cloud Functions?

I am using an https triggered Google Cloud Function that is supposed to download a file from Google Cloud Storage (and then combine it with data from req.body). While it seems to work as long as the downloaded file is in the root directory I am having problems accessing the same file when placed inside a folder. The path to the file is documents/someTemplate.docx

'use strict';
const functions = require('firebase-functions');
const path = require('path');
const os = require("os");
const fs = require('fs');
const gcconfig = {
  projectId: "MYPROJECTNAME",
  keyFilename: "KEYNAME.json"
};
const Storage = require('@google-cloud/storage')(gcconfig)
const bucketPath = 'MYPROJECTNAME.appspot.com'
const bucket = Storage.bucket(bucketPath);

exports.getFileFromStorage = functions.https.onRequest((req, res) => {
      let fileName = 'documents/someTemplate.docx'
      let tempFilePath = path.join(os.tmpdir(), fileName);

      return bucket.file(fileName)
      .download({
          destination: tempFilePath,
        })
        .then(() => {
          console.log(fileName + ' downloaded locally to', tempFilePath);
          let content = fs.readFileSync(tempFilePath, 'binary');

          // do stuff with the file and data from req.body

          return
        })
        .catch(err => {
          res.status(500).json({
            error: err
          });
        });
})

What I don't understand is that when I move the file to the root directory and use the file name someTemplate.docx instead then the code works.

Google's documentation states that

Objects added to a folder appear to reside within the folder in the GCP Console. In reality, all objects exist at the bucket level, and simply include the directory structure in their name. For example, if you create a folder named pets and add a file cat.jpeg to that folder, the GCP Console makes the file appear to exist in the folder. In reality, there is no separate folder entity: the file simply exists in the bucket and has the name pets/cat.jpeg.

This seems to be correct as in the metadata the file name is indeed documents/someTemplate.docx. Therefore I don't understand why the code above does not work.

Upvotes: 1

Views: 1791

Answers (1)

Stu
Stu

Reputation: 148

Posting comment answer from @James Poag for visibility:

Also, perhaps the directory doesn't exist on the temp folder location? Maybe try let tempFilePath = path.join(os.tmpdir(), 'tempkjhgfhjnmbvgh.docx'); – James Poag Aug 21 at 17:10

Upvotes: 1

Related Questions