最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to delete all files in a firebase storage directory - Stack Overflow

programmeradmin0浏览0评论

I have a firebase storage path that looks like this.

firebase.storage().ref('temp/test')

the "test" folder has about 25-50 files. I know there is not a way to delete the whole directory in firebase but Is there a way to iterate through all the files in a directory and deleting them one by one?

I have a firebase storage path that looks like this.

firebase.storage().ref('temp/test')

the "test" folder has about 25-50 files. I know there is not a way to delete the whole directory in firebase but Is there a way to iterate through all the files in a directory and deleting them one by one?

Share Improve this question edited Aug 23, 2023 at 10:31 Renaud Tarnec 83.2k10 gold badges98 silver badges129 bronze badges Recognized by Google Cloud Collective asked Aug 16, 2020 at 7:24 Manan SharmaManan Sharma 5711 gold badge5 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

Is there a way to iterate through all the files in a directory and deleting them one by one?

Yes, you can use the listAll() method, as follows:

  const storageRef = firebase.storage().ref('temp');
  storageRef.listAll().then((listResults) => {
    const promises = listResults.items.map((item) => {
      return item.delete();
    });
    Promise.all(promises);
  });

Note that:

  1. This method is only available for Firebase Rules Version 2 (add rules_version = '2'; at the top of the Security Rules).
  2. This is a helper method for calling list() repeatedly until there are no more results. The default pagination size is 1000.

I did it this way in my Angular app (tree-shakable calls / modular api):

import {
   Storage, ref, getStorage, listAll, deleteObject, getBytes
} from '@angular/fire/storage';
  ...
  async deleteDirectory(directoryPath: string) {
    const storage = getStorage();
    const listRef = ref(storage, directoryPath);
    await this.deleteFiles(listRef);
  }

  async deleteFiles(listRef: any) {
    await listAll(listRef)
      .then((res) => {
        res.prefixes.forEach((folderRef) => {
          // if list item is a directory, recursively move through directory tree
          this.deleteFiles(folderRef);
        });
        res.items.forEach((itemRef) => {
          // if not a directory or empty, delete object
          deleteObject(itemRef);
        });
      }).catch((error) => {
        console.log('error deleting storage objects: ', error);
    });
  }
发布评论

评论列表(0)

  1. 暂无评论