Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Medium
  • Last Updated : 17 Dec, 2020

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 –

  1. Get the reference to the storage using refFromUrl method from firebase.storage.
  2. 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 URL as an input – 

  1. gs:// URL, for example, gs://bucket/files/image.png
  2. Download URL taken from object metadata.

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

Javascript






var fileUrl = 
  
// Create a reference to the file to delete
var 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
var 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



My Personal Notes arrow_drop_up
Recommended Articles
Page :