Bryan Deemer
Bryan Deemer

Reputation: 913

How can I get a list of files in my storage bucket using Firebase Functions

I'm trying to write a simple function that will iterate over all the files I have in a folder in Firebase storage using a Firebase Cloud Function. I have spent hours trying every example online and reading the documentation.

This is what I currently have:

exports.removeUnsizedImages = functions.pubsub.schedule('every 2 minutes').onRun((context) => {

    const storage = admin.storage();
    var storageRef = storage.ref();

    storageRef.listAll().then(function(result) {
        console.log("*", result);
    })
});

I'm getting an error that storage.ref() is not a function.

If I try:

storage.listAll()

It also tells me that listAll is not a function.

I really didn't think it would be this hard to just get the files in a folder.

What am I doing wrong?

UPDATED CODE THAT NOW WORKS

exports.removeUnsizedImages = functions.pubsub.schedule('every 24 hours').onRun((context) => {
    
    admin.storage().bucket().getFiles({ prefix: "postImages/" }).then(function(data) {
        const files = data[0];

        files.forEach(function(image) {
            console.log("***** ", image.name)
        })

    });
    
});

Upvotes: 2

Views: 2416

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50930

The listAll you are using is a function in the Firebase Storage Client SDK and not the Admin SDK.

To get all files in the Admin SDK, try this:

const allFiles = await admin.storage().bucket().getFiles({ prefix: "/user/images" })

Here prefix is the path which you want to list.

  • If you just specify prefix = 'a/', you'll get back:
  • /a/1.txt
  • /a/b/2.txt
  • However, if you specify prefix='a/' and delimiter='/', you'll get back:
  • /a/1.txt

You can just use .getFiles() to get the whole bucket. More details can be found in the documentation

Upvotes: 6

Related Questions