【问题标题】:How to Delete a blob from Azure blob v12 SDK for Node.js如何从适用于 Node.js 的 Azure blob v12 SDK 中删除 blob
【发布时间】:2020-06-28 04:57:57
【问题描述】:
【问题讨论】:
标签:
node.js
azure
azure-blob-storage
【解决方案1】:
正如@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);
});
运行此示例后,test.txt 文件已从 test 容器中删除。
【解决方案2】:
虽然杰克的答案有效,但它比需要的复杂。与其创建 blockBlobClient 然后删除它,更简单的方法是使用:
containerClient.deleteBlob('blob-name')