skip to Main Content

I’m try to apply Google Cloud Vision to files in my Firebase Cloud Storage using Firebase Cloud Functions.
The storage structure is bucket > images > userID > image. There are multiple users and they have multiple images in their folder. I want to be able to map/forEach the userID and then map/forEach the images. I am struggling to figure out how to go about this.

I have tried: List Objects In a Bucket but its not working, probably because its for GCP rather than Firebase functions.

How do I iterate over objects in a Firebase bucket?

2

Answers


  1. buckets are very similar to filesystems. i believe in firebase you’re looking for something like /images/[userID]/[filename]

    it should be pretty easy just to use your framework to do this. it’s unlikely you’ll need any ADDITIONAL firebase functions.

    Login or Signup to reply.
  2. At first you should note that Google Cloud Storage does not have genuine "folders". In the Cloud Storage console, the files in your bucket are presented in a hierarchical tree of folders (just like the file system on your local hard disk) but this is just a way of presenting the files: there aren’t genuine folders/directories in a bucket.

    The Cloud Storage console just uses the different parts of the file paths to "simulate" a folder structure, by using the "/" delimiter character.

    This doc on Cloud Storage and gsutil explains and illustrates very well this "illusion of a hierarchical file tree".


    So you can very well use the asynchronous getFiles() method to list the files in your bucket, but:

    • For each file you’ll get its full path and it will be up to you to extract the parent "folders" names and the file name from this path in order to get the desired result (forEach loops mentioned in your question)
    • In addition you’ll also get the "folders" name

    As an example, the following HTTPS Cloud Function lists all the files (and "folders") in your default bucket: it log them in the Cloud Console Log and it returns an array of all these files.

    const { onRequest } = require("firebase-functions/v2/https");
    const { log } = require("firebase-functions/logger");
    
    // The Firebase Admin SDK to access Firestore.
    const { initializeApp } = require("firebase-admin/app");
    const { getStorage } = require("firebase-admin/storage");
    
    initializeApp();
    
    exports.getFilesList = onRequest(async (req, res) => {
      const fileBucket = getStorage().bucket();
      const [files] = await fileBucket.getFiles();
    
      const filesArray = [];
      files.forEach((file) => {
        log(file.name);
        filesArray.push(file.name);
      });
    
      res.send({ bucketName: filesArray });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search