Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Storage-How to delete file from storage with node.js?

I want to delete a folder in firebase storage with node js because this is a firebase function.

For example :

storageRef.child(child1).child(child2).delete();

something like this, but firebase documentation doesn't tell anything.

One more question: When initialize storage documentation node js requires my admin json, but realtime database doesn't want this wonder why?

like image 416
uzaysan Avatar asked Jan 08 '19 10:01

uzaysan


People also ask

How do you delete data from Storage on Firebase?

To delete a file, first create a reference to that file. Then call the delete() method on that reference, which returns a Promise that resolves, or an error if the Promise rejects. Learn more about the tree-shakeable Web v9 modular SDK and upgrade from version 8.

How do you delete a file in node JS?

js fs-extra remove() Function. the remove() function deletes the given file or directory. All the files inside a directory are deleted.


3 Answers

Have a look at the Node.js client API Reference for Google Cloud Storage and in particular at the delete() method for a File.

like image 117
Renaud Tarnec Avatar answered Oct 08 '22 01:10

Renaud Tarnec


You can do it like this using Node.js:

const firebase = require('firebase-admin');

async function deleteImageFromFirebase(imageName) {
    await firebase.storage().bucket().file("folderName/"+imageName).delete();
}

And like this client side:

// Create a reference to the file to delete
var desertRef = storageRef.child('images/desert.jpg');

// Delete the file
desertRef.delete().then(function() {
  // File deleted successfully
}).catch(function(error) {
  // Uh-oh, an error occurred!
});

View this info on the Firebase website: how to delete files Firebase-storage

like image 41
Dustin Spengler Avatar answered Oct 07 '22 23:10

Dustin Spengler


This might be late but at least on Web (so basically what you need), there is new API to delete the whole folder.

I tested deleting a folder with 2 pictures inside and it works. I then tried a folder-A with contents: folder-B + picture-A. Folder-B also has a picture-B inside; it still deleted folder-A with all of its contents.

Solution:

const bucket = admin.storage().bucket();

return bucket.deleteFiles({
  prefix: `posts/${postId}`
);

I couldn't find this on the official documentation (perhaps is really new API) but really cool article where I found the solution: Automatically delete your Firebase Storage Files from Firestore with Cloud Functions for Firebase

like image 1
Marius Mircea Avatar answered Oct 08 '22 01:10

Marius Mircea