node.js - 获取 Azure Blob 存储中可用元素数量的总文件大小

标签 node.js mongodb azure

我正在尝试获取容器内每个用户可用的文件的总大小。我正在使用 map 函数进行迭代,当我尝试控制台记录值时,它会正确显示它们,但在 map 函数完成后它会给出 0。任何帮助将不胜感激。


const connString: string = process.env.AZURE_STORAGE_CONNECTION_STRING!;

const blobServiceClient = BlobServiceClient.fromConnectionString(
  connString
);

const containerClient = blobServiceClient.getContainerClient("mycontainer");

 try {
      let userId = req.params["user_id"];
      let storageInfo: any = await AddToHiveModel.find({ user_id: userId });
      let storageInfoTotal: number = 0;

      console.log(storageInfo.length);
      await AddToHiveModel.find({ user_id: userId }).then((result:any)=> {
        if(result.length > 0){
          result.map( async (element: any) => {
            let blobName = `uploads/${element.user_id}/${element.filename}`;
            await containerClient.getBlobClient(blobName).getProperties()
              .then(
                (result: any) => {
                  storageInfoTotal += Number(result.contentLength);
                })
              .catch((err: any) => {
                return err;
              });
            
            return null;
  
          }
          );
          console.log(storageInfoTotal);
          resp.json(storageInfoTotal);
        }else {
          resp.json(storageInfoTotal);
        }
      });

    } catch (err) {
      console.error("Caught error", err);
      resp.status(500).send(err);
      resp.end();
    }

最佳答案

尝试获取 blob 的属性。

var blob = _container.GetBlockBlobReference(blobName);
if (blob.Exists())
{
    blob.FetchAttributes();
    return blob.Properties.Length;
}

throw new Exception("Blob doesn't exist");

尝试使用此代码来确定 blob 的大小:

val blob: CloudBlockBlob = container.getBlockBlobReference(blobPath)
blob.downloadAttributes()
blob.getProperties.getLength

为避免属性为空,请确保调用 downloadAttributes。

引用文献:

  1. Calculate blob count and total size per container using Azure Storage inventory
  2. Calculate the size/capacity of storage account and it services
  3. CloudBlockBlob Class

关于node.js - 获取 Azure Blob 存储中可用元素数量的总文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72852213/

相关文章:

javascript - Nodejs 结合了我的 sql 命令的两个结果

php - 大型用户电子邮件/消息系统的良好设计模式或开源软件?

javascript - 无法让 mongoose-unique-validator 工作

node.js - Nodejs用户登录系统

javascript - 规则和夏令时

node.js - 如何禁用 jade 或 swig 中的缓存

mongodb - mongodb 错误 : "getFile(): bad file number value (corrupt db?): run repair"

azure - 动态访问从云服务上传到Azure门户的证书

azure - 如何将文件保存到 Azure blob 容器中的子文件夹?

asp.net-mvc-3 - Azure 和 MVC 中的成员角色