'Firebase: Cloud Functions + Storage Read File

I am currently writing a function in Firebase Functions to be called within my Firebase mobile application. I have the code to call the function, but I do not know how to get this function to interact with Firebase storage.

I have a JSON file (300KB) of public non-sensitive information stored in a Firebase Storage bucket. Based on user input, I will select specific attributes of this JSON file and return the result to the user. However, I cannot figure out how to read this file from my Firebase Functions code. How do I do the following? Also, if anyone knows a more cost-effective way to do this, please let me know!!

exports.searchJSON = functions.https.onCall((data, context) => {
    const keyword = data.searchTerm
    //search the JSON file that is present in the storage bucket
    //save the sliced JSON object as a variable
    //return this to the user
})


Solution 1:[1]

You have 2 options that you can use. See options below.

  1. Firebase Admin

    const { initializeApp } = require('firebase-admin/app');
    const { getStorage } = require('firebase-admin/storage');
    
    initializeApp({
      storageBucket: '<BUCKET_NAME>.appspot.com'
    });
    
    const bucket = getStorage().bucket().file("<FILE-PATH>")
    .download(function (err, data) {
        if (!err) {
            var object = JSON.parse(data)
            console.log(object);
        }
    });
    

    Make sure you've installed the Admin SDK module.

    npm i firebase-admin
    
  2. Google Cloud Storage SDK

    const {Storage} = require('@google-cloud/storage');
    
    const storage = new Storage();
    const fileBucket = '<BUCKET-NAME>.appspot.com';
    const filePath = '<FILE-PATH>';
    const bucket = storage.bucket(fileBucket);
    const file = bucket.file(filePath);
    
    file.download()
    .then((data) => {
    const object = JSON.parse(data);
    console.log(object);
    });
    

    Make sure you've installed the @google-cloud/storage module:

    npm i @google-cloud/storage
    

For more information, you may check out these documentations:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marc Anthony B