如何从Azure blob v12 SDK for Node.js中删除blob

ih99xse1  于 2023-10-17  发布在  Node.js
关注(0)|答案(3)|浏览(146)

如何通过Node.js删除Azure Blob,并且我正在使用Azure library v12 SDK for Node.js(https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-nodejs
我找不到删除blob方法,我想按名称删除blob。

du7egjpx

du7egjpx1#

虽然杰克的答案是有效的,但它比实际需要的要复杂得多。与其创建blockBlobClient然后删除它,更简单的方法是使用:用途:
containerClient.deleteBlob('blob-name')

jv4diomz

jv4diomz2#

正如@Georage在评论中所说,你可以使用delete方法来删除一个blob。
以下是我的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);
  });

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

ybzsozfc

ybzsozfc3#

@JackJia的答案是完美的作品!

这是我的ES6 JavaScript : Typescript :)代码
我把它作为一个单独的功能。所以我只能把blob的名字传递给它。

import { BlobServiceClient } from "@azure/storage-blob";
import dotenv from "dotenv";

dotenv.config();

const azureBlobServiceClient = BlobServiceClient.fromConnectionString(
  process.env.AZURE_STORAGE_CONNECTION_STRING!
);
const containerClient = azureBlobServiceClient.getContainerClient(
  process.env.BLOB_CONTAINER_NAME!
);

export const deleteBlob = async (blobName: string) => {
  const blobClient = containerClient.getBlockBlobClient(blobName);
  await blobClient.delete();
};

blobName传递给函数&它将处理所有其他事情:)
仅供参考:确保将String类型传递给blobName。否则 typescript 会哭:(

相关问题