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

Meh*_*lal 4 azure azure-storage-blobs node.js

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

我找不到删除 blob 方法,我想按名称删除 blob。

L_H*_*L_H 12

虽然杰克的答案有效,但它比需要的更复杂。与其创建blockBlobClient然后删除它,更简单的方法是使用:

containerClient.deleteBlob('blob-name')


Jac*_*Jia 6

正如@Georage 在评论中所说,您可以使用该delete方法删除一个 blob。

这是我的演示:

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);
  });
Run Code Online (Sandbox Code Playgroud)

运行此示例后,该test.txt文件已从test容器中删除。