4
votes

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)

I could not find delete blob method, I want to delete blob by name.

2

2 Answers

6
votes

Just as @Georage said in the comment, you can use the delete method to delete a 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.

4
votes

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:

containerClient.deleteBlob('blob-name')