How to delete file from the firebase using file url in node.js ?
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 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 URL as an input –
- gs:// URL, for example, gs://bucket/files/image.png
- 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
Please Login to comment...