how to check if file exists in Firebase Storage?

23,482

Solution 1

Firebase added an .exists() method. Another person responded and mentioned this, but the sample code they provided is incorrect. I found this thread while searching for a solution myself, and I was confused at first because I tried their code but it always was returning "File exists" even in cases when a file clearly did not exist.

exists() returns an array that contains a boolean. The correct way to use it is to check the value of the boolean, like this:

const storageFile = bucket.file('path/to/file.txt');
storageFile
  .exists()
  .then((exists) => {
        if (exists[0]) {
          console.log("File exists");
        } else {
          console.log("File does not exist");
        }
     })

I'm sharing this so the next person who finds this thread can see it and save themselves some time.

Solution 2

You can use getDownloadURL which returns a Promise, which can in turn be used to catch a "not found" error, or process the file if it exists. For example:

storageRef.child("file.png").getDownloadURL().then(onResolve, onReject);

function onResolve(foundURL) {
    //stuff
}

function onReject(error) {
    console.log(error.code);
}

Solution 3

I believe that the FB storage API is setup in a way that the user only request a file that exists.

Thus a non-existing file will have to be handled as an error: https://firebase.google.com/docs/storage/web/handle-errors

Solution 4

I've found a nice solution while keeping within the Node.js Firebase Gogole Cloud Storage SDK using the File.exists, taught it would be ideal to share for those searching.

const admin = require("firebase-admin");
const bucket = admin.storage().bucket('my-bucket');

const storageFile = bucket.file('path/to/file.txt');
storageFile
  .exists()
  .then(() => {
    console.log("File exists");
  })
  .catch(() => {
    console.log("File doesn't exist");
  });

Google Cloud Storage: Node.js SDK version 5.1.1 (2020-06-19) at the time of writing

Share:
23,482
Pier
Author by

Pier

Updated on July 09, 2022

Comments

  • Pier
    Pier almost 2 years

    When using the database you can do snapshot.exists() to check if certain data exists. According to the docs there isn't a similar method with storage.

    https://firebase.google.com/docs/reference/js/firebase.storage.Reference

    What is the proper way of checking if a certain file exists in Firebase Storage?

  • Corentin Houdayer
    Corentin Houdayer almost 4 years
    Warning: might be costly if you have several thousands of documents as downloading url will be priced by Firebase.
  • Pier
    Pier over 3 years
    The example code is wrong. Check the example on the docs: googleapis.dev/nodejs/storage/5.1.1/File.html#exists-example‌​s
  • Grant Singleton
    Grant Singleton about 3 years
    Thanks for this. Is there any Google documentation for this method? I can't seem to find it.
  • most200
    most200 about 3 years
    @GrantSingleton I have not been able to find any official documentation on it myself either.
  • most200
    most200 about 3 years
    @GrantSingleton Correction: there is one reference. Another poster shared it in a comment further down on this same topic, if you scroll down. googleapis.dev/nodejs/storage/5.1.1/File.html#exists-example‌​s
  • Patrick Michaelsen
    Patrick Michaelsen about 3 years
    make sure to check exists[0] and not exists. that was my ire
  • Tyler2P
    Tyler2P almost 3 years
    A good answer will always include an explanation why this would solve the issue, so that the OP and any future readers can learn from it
  • Brandon Pillay
    Brandon Pillay almost 3 years
    Where does bucket come from?
  • most200
    most200 almost 3 years
    @BrandonPillay For me it comes from: const fbAdmin = require('firebase-admin'); const bucketName = projectId + '.appspot.com'; const bucket = fbAdmin.storage().bucket(bucketName);
  • Abu Saeed
    Abu Saeed about 2 years
    @CorentinHoudayer He is giving reference with file_name. So there is only one file. Why will it be costly?
  • Corentin Houdayer
    Corentin Houdayer about 2 years
    @Unknown2433 If you download only this document once in your app for a single user, the answer is no. If you do it multiple times (each app launch) with multiple files, yes it will become pretty expensive. Take a look at firebase pricing and you can estimate your budget based on this.
  • Abu Saeed
    Abu Saeed about 2 years
    @CorentinHoudayer I am not downloading the file. I am requesting for the download url of the file and calling getDownloadUrl is free. Isn't it?
  • Corentin Houdayer
    Corentin Houdayer about 2 years
    @Unknown2433 It isn't free as you will consume bandwidth which has a cost. I had an app where I was showing wallpapers, using this request 50 times / per session on average was really expensive for me. Even more if you download the file using URL of course. In order to know the consumed bandwidth, you might do your own test on Android with a specific app for instance.
  • Abu Saeed
    Abu Saeed about 2 years
    @CorentinHoudayer I know about bandwidth cost which is the worst thing about firebase storage. But I didn't knew that calling getDownloadUrl uses bandwidth. Thanks for the info
  • dovigz
    dovigz about 2 years
    are there any costs associated with this method?
  • most200
    most200 about 2 years
    @dovigz I'm not sure on costs. Here is the link to cloud storage pricing: cloud.google.com/storage/pricing#pricing To me it feels like exists() could be a class B operation (which cost $.004 per 10k in 2022 pricing), but it is not explicitly listed. Firebase also includes 50k free operations per month. I don't use exists at a high enough volume to see any impact on my current costs. You could try running a quantity of exists operations to see if they show up in your billing, or contact Firebase support to ask if they can clarify.