how to check if file exists in Firebase Storage?

前端 未结 3 1449
渐次进展
渐次进展 2020-12-30 21:32

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.

相关标签:
3条回答
  • 2020-12-30 22:07

    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

    0 讨论(0)
  • 2020-12-30 22:22

    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

    0 讨论(0)
  • 2020-12-30 22:25

    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);
    }
    
    0 讨论(0)
提交回复
热议问题