获取在 Firebase 存储中的文件夹中使用的存储 space

Get storage space used in a folder in Firebase Storage

我正在创建一个 Firebase 应用程序,您可以使用它来上传文件。如何获取用户在其文件夹 (users/{userId}/{allPaths=**}) 中使用的 space 数量?

好问题。简而言之,没有简单的方法来做到这一点(即使对我们来说也是如此!)因为这实际上要求我们递归整个文件集并将它们全部加起来。这是一个相当大的 mapreduce,每次上传文件时 运行 效率不高。

但是,return metadata.size 属性 中单个文件的大小,因此您可以在服务器上执行自己的 list 调用(查看在 gcloud`),它会给你一个文件列表和 "folders"。获取文件的大小并将它们相加,然后递归并对所有子文件夹执行相同的操作。把它们总结起来,写成类似 Firebase Realtime Database 的东西,在那里你可以很容易地从客户端获取文件夹大小。

这是我写的一个小脚本,它计算用于每个 "folders" 的文件和字节数并输出到控制台。

function main(bucketName = 'YOUR_BUCKET_NAME') {
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const bucketName = 'Name of a bucket, e.g. my-bucket';

  // Imports the Google Cloud client library
  const {Storage} = require('@google-cloud/storage');

  // Creates a client
  const storage = new Storage();

  async function listFiles() {
    // Lists files in the bucket
    const [files] = await storage.bucket(bucketName).getFiles();

    console.log('Files:');
    let bucketList = {};
    files.forEach(file => {
      let folder = file.name.split('/')[0];
      if (!bucketList[folder]) {
        bucketList[folder] = {};
        bucketList[folder]['bytes'] = 0;
        bucketList[folder]['count'] = 0;
      }
      bucketList[folder]['bytes'] += Number(file.metadata.size);
      bucketList[folder]['count'] +=1;

    });
    console.log(bucketList);
  }

  listFiles().catch(console.error);
  // [END storage_list_files]
}
main(...process.argv.slice(2));

基于@Mike 的回答的略微改进的版本,它还递归地输出所有子文件夹的大小,并以“人类可读”格式打印大小,即 MB、kB 等

它还会将输出写入 json 文件,您可以使用一些 json 查看器(例如 https://jsoneditoronline.org/.

来探索该文件

请注意,您还需要将 serviceaccount.json 作为凭据传递给 Storage

function main(bucketName) {


    // Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');
const fs = require('fs').promises;
// Creates a client
const storage = new Storage({
    credentials: //your service account json key
});



async function listFiles() {
    // Lists files in the bucket
    const [files] = await storage.bucket(bucketName).getFiles();

    console.log('Files:');
    let bucketList = {};
    files.forEach(file => {
        let folders = file.name.split('/');
        let curFolder = bucketList
        folders.forEach(subFolder => {
            if (!curFolder[subFolder]) {
                curFolder[subFolder] = {};
                curFolder[subFolder]['bytes'] = 0;
                curFolder[subFolder]['count'] = 0;
            }
            curFolder[subFolder]['bytes'] += Number(file.metadata.size);
            curFolder[subFolder]['count'] +=1;
            curFolder[subFolder]['size'] = humanFileSize(curFolder[subFolder]['bytes'])
            curFolder = curFolder[subFolder]
        })

    });
    console.log(bucketList);
    await fs.writeFile("sizes.json", JSON.stringify(bucketList))
}

function humanFileSize(bytes, si=true, dp=1) {
    const thresh = si ? 1000 : 1024;

    if (Math.abs(bytes) < thresh) {
        return bytes + ' B';
    }

    const units = si
        ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
        : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
    let u = -1;
    const r = 10**dp;

    do {
        bytes /= thresh;
        ++u;
    } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);


    return bytes.toFixed(dp) + ' ' + units[u];
}

listFiles().catch(console.error);
// [END storage_list_files]
}

//TODO change the name of the bucket to yours

main("my-bucket-name");