2

So I am working on a loop and I am wondering whats the recommended way to deal with situations where you are looping through a bunch of firebase storage items and you are going to use bunch of firebase child refs. I am using Node.js 12.18.2 and I am writing function for firebase cloud functions and I am going to loop through a bunch of files stored inside firebase storage and I wanna keep variable hoisting in mind while writing the code.

//should I put the ref here? and ofc, which one is better to use var or let?
let storageRef = firebase.storage();
var storageRef = firebase.storage();

item.forEach(element => {
// or use seperate storage ref for each firebase storage item
let storageRef = firebase.storage();
var storageRef = firebase.storage();

let storageRef.child("images/stars.jpg").getDownloadURL(); //bla bla bla
});

basically don't want the storage ref to somehow collide with each other. what's the best option?

  • Are you using this code in a Cloud Function? If yes, can you share the entire code of the Cloud Function, including the import at the top of your CF file and how you initialize the Admin SDK. – Renaud Tarnec Oct 04 '20 at 17:15
  • @RenaudTarnec yea I wrote that in the description –  Oct 04 '20 at 17:17

1 Answers1

1

firebase.storage() returns the same singleton object that will not change over the lifetime of the initialized firebase object. It costs essentially nothing to access it. If you want to reuse that object, it makes more sense to use const to declare it at the top level of your program so your code makes it clear that the variable will never change after it's assigned.

Also I would not call it storageRef, since a Reference is a special type of object in Cloud Storage (which you get when you call child()), which I wouldn't want to confuse with this singleton object.

const storage = firebase.storage();

Lastly, it looks like you're using the JavaScript client SDK in Cloud Functions, which could be problematic. You should consider using the nodejs SDK instead, which will be easier to work with in Cloud Functions, and also give you full admin access to your storage bucket. If you want to create a download URL, you should use a different strategy.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Hey I am trying to use the cloud functions to access a file and update it and then paste it back into a different folder, whats the best way? –  Oct 05 '20 at 14:02
  • I am getting this error trying to use firebase.storage() in node js `TypeError: firebase.storage is not a function` –  Oct 05 '20 at 15:33