2

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)
        })

    });
    
});
1
  • 1
    You should returned the promises returned by the asynchronous work, see firebase.google.com/docs/functions/terminate-functions. Something like return admin.storage().bucket().getFiles({ prefix: "postImages/" }).then(function(data) { const files = data[0]; ... return null; }); Commented May 23, 2021 at 12:48

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much! This was exactly what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.