Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

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

like image 897
MJ X Avatar asked Mar 17 '20 05:03

MJ X


People also ask

What should you use to automatically delete blobs from Azure blob storage?

We are pleased to announce that we have made an Azure Logic Apps template available to expire old blobs. To set up this automated solution in your environment: Create a new Logic Apps instance, select the “Delete old Azure blobs” template, customize and run.


Video Answer


1 Answers

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.

like image 191
Jack Jia Avatar answered Oct 10 '22 09:10

Jack Jia