Delete and restore a blob in your Azure Storage account using the JavaScript client library

This article shows how to delete blobs with the Azure Storage client library for JavaScript. If you've enabled blob soft delete, you can restore deleted blobs.

The sample code snippets are available in GitHub as runnable Node.js files.

Note

The examples in this article assume that you've created a BlobServiceClient object by using the guidance in the Get started with Azure Blob Storage and JavaScript article. Blobs in Azure Storage are organized into containers. Before you can upload a blob, you must first create a container. To learn how to create a container, see Create a container in Azure Storage with JavaScript.

Delete a blob

To delete a blob, create a BlobClient then call either of these methods:

The following example deletes a blob.

async function deleteBlob(containerClient, blobName){

  // include: Delete the base blob and all of its snapshots.
  // only: Delete only the blob's snapshots and not the blob itself.
  const options = {
    deleteSnapshots: 'include' // or 'only'
  }

  // Create blob client from container client
  const blockBlobClient = await containerClient.getBlockBlobClient(blobName);

  await blockBlobClient.delete(options);

  console.log(`deleted blob ${blobName}`);

}

The following example deletes a blob if it exists.

async function deleteBlobIfItExists(containerClient, blobName){

  // include: Delete the base blob and all of its snapshots.
  // only: Delete only the blob's snapshots and not the blob itself.
  const options = {
    deleteSnapshots: 'include' // or 'only'
  }

  // Create blob client from container client
  const blockBlobClient = await containerClient.getBlockBlobClient(blobName);

  await blockBlobClient.deleteIfExists(options);

  console.log(`deleted blob ${blobName}`);

}

Restore a deleted blob

Blob soft delete protects an individual blob and its versions, snapshots, and metadata from accidental deletes or overwrites by maintaining the deleted data in the system for a specified period of time. During the retention period, you can restore the blob to its state at deletion. After the retention period has expired, the blob is permanently deleted. For more information about blob soft delete, see Soft delete for blobs.

You can use the Azure Storage client libraries to restore a soft-deleted blob or snapshot.

Restore soft-deleted objects when versioning is disabled

To restore deleted blobs, create a BlobClient then call the following method:

This method restores soft-deleted blobs and any deleted snapshots associated with it. Calling this method for a blob that has not been deleted has no effect.

async function undeleteBlob(containerClient, blobName){

  // Create blob client from container client
  const blockBlobClient = await containerClient.getBlockBlobClient(blobName);

  await blockBlobClient.undelete();

  console.log(`undeleted blob ${blobName}`);

}

See also