Open In App

How to delete file from the firebase using file url in node.js ?

Last Updated : 07 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

To delete a file from the Firebase storage we need a reference to store the file in storage. As we only have the file URL we need to create a reference object of the file in Firebase storage and then delete that file.

Deleting a file using the file URL can be done in two steps –

  • Get the reference to the storage using the refFromUrl method from Firebase. storage.
  • Deleting the file using the reference of the file in storage obtained from Step 1.

The method refFromUrl returns a reference to that file and can take two types of file URLs as input – 

  • gs:// URL, for example, gs://bucket/files/image.png
  • The download URL is taken from object metadata.

Example 1: Deleting a file from the given file URL using the refFromURL method.

Javascript




const fileUrl =
  
// Create a reference to the file to delete
const fileRef = storage.refFromURL(fileUrl);
  
console.log("File in database before delete exists : "
            + fileRef.exists())
  
// Delete the file using the delete() method
fileRef.delete().then(function () {
  
    // File deleted successfully
    console.log("File Deleted")
}).catch(function (error) {
    // Some Error occurred
});
  
console.log("File in database after delete exists : "
            + fileRef.exists())


Output:

File in database before delete exists : true
File Deleted
File in database after delete exists : false

Example 2: Deleting a file using bucket gs:// URL 

Javascript




// gs Bucket URL
  
// Create a reference to the file to delete
const fileRef = storage.refFromURL(fileUrl);
  
console.log("File in database before delete exists : "
            + fileRef.exists())
  
// Delete the file using the delete() method
fileRef.delete().then(function () {
  
    // File deleted successfully
    console.log("File Deleted")
}).catch(function (error) {
    // Some Error occurred
});
  
console.log("File in database after delete exists : "
        + fileRef.exists())


Output :

File in database before delete exists : true
File Deleted
File in database after delete exists : false


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads