how to check if file exists in Firebase Storage?
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);
}
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.