简体   繁体   English

如何从适用于 Node.js 的 Azure blob v12 SDK 中删除 blob

[英]How to Delete a blob from Azure blob v12 SDK for Node.js

How can I delete Azure Blob through Node.js and I am using Azure library v12 SDK for Node.js ( https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-nodejs )如何通过 Node.js 删除 Azure Blob,并且我正在使用适用于 Node.js 的 Azure 库 v12 SDK ( https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-nodejs )

I could not find delete blob method, I want to delete blob by name.我找不到删除 blob 方法,我想按名称删除 blob。

Just as @Georage said in the comment, you can use the delete method to delete a blob.正如@Georage 在评论中所说,您可以使用delete方法删除一个 blob。

Here is my demo:这是我的演示:

const { BlobServiceClient,ContainerClient, StorageSharedKeyCredential } = require("@azure/storage-blob");

// Load the .env file if it exists
require("dotenv").config();

async function streamToString(readableStream) {
    return new Promise((resolve, reject) => {
      const chunks = [];
      readableStream.on("data", (data) => {
        chunks.push(data.toString());
      });
      readableStream.on("end", () => {
        resolve(chunks.join(""));
      });
      readableStream.on("error", reject);
    });
  }

async function main() {
    const AZURE_STORAGE_CONNECTION_STRING = process.env.AZURE_STORAGE_CONNECTION_STRING;
    const blobServiceClient = await BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);
    const containerClient = await blobServiceClient.getContainerClient("test");
    const blockBlobClient = containerClient.getBlockBlobClient("test.txt")
    const downloadBlockBlobResponse = await blockBlobClient.download(0);
    console.log(await streamToString(downloadBlockBlobResponse.readableStreamBody));
    const blobDeleteResponse = blockBlobClient.delete();
    console.log((await blobDeleteResponse).clientRequestId);
}

main().catch((err) => {
    console.error("Error running sample:", err.message);
  });

After running this sample, the test.txt file was removed from the test container.运行此示例后, test.txt文件已从test容器中删除。

While Jack's answer works, it is more complicated than it needs to be.虽然杰克的答案有效,但它比实际需要的要复杂得多。 Instead of creating the blockBlobClient and then deleting it, a simpler way would be to use:而不是创建blockBlobClient然后删除它,一种更简单的方法是使用:

containerClient.deleteBlob('blob-name')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM