使用 JavaScript 或 TypeScript 刪除和還原 Blob 容器
本文說明如何使用適用於 JavaScript 的 Azure 儲存體用戶端程式庫來刪除容器。 如果您已啟用容器虛刪除,則可以還原已刪除的容器。
必要條件
- 本文中的範例假設您已設定專案,以搭配使用適用於 JavaScript 的 Azure Blob 儲存體用戶端程式庫。 若要了解如何設定專案,包括套件安裝、匯入模組,以及建立授權的用戶端物件來處理資料資源,請參閱開始使用 Azure Blob 儲存體和 JavaScript。
- 授權機制必須具有刪除 Blob 容器的權限,或還原虛刪除容器的權限。 若要深入了解,請參閱下列 REST API 作業的授權指導:
刪除容器
若要刪除容器,請使用 BlobServiceClient 類別中的下列方法:
您也可以使用 ContainerClient 類別的下列方法刪除容器:
刪除容器之後,您就無法建立具有相同名稱的容器至少 30 秒。 嘗試建立具有相同名稱的容器會失敗,並出現 HTTP 錯誤碼 409 (Conflict)
。 對容器或其包含的 Blob 進行的任何其他作業都會失敗,並出現 HTTP 錯誤碼 404 (Not Found)
。
下列範例使用 BlobServiceClient
物件來刪除指定容器:
async function deleteContainer(blobServiceClient, containerName) {
return await blobServiceClient.deleteContainer(containerName);
}
下列範例顯示如何刪除以指定前置詞開頭的所有容器:
async function deleteContainersWithPrefix(blobServiceClient, prefix) {
const containerOptions = {
includeDeleted: false,
includeMetadata: false,
includeSystem: true,
prefix
}
for await (const containerItem of blobServiceClient.listContainers(containerOptions)) {
try{
const containerClient = blobServiceClient.getContainerClient(containerItem.name);
await containerClient.delete();
console.log(`Deleted ${containerItem.name} container - success`);
}catch(ex){
console.log(`Deleted ${containerItem.name} container - failed - ${ex.message}`);
}
}
}
還原已刪除的容器
針對記憶體帳戶啟用容器虛刪除時,可以在您指定的保留期間內,復原容器及其內容。 您可以使用 BlobServiceClient 物件還原虛刪除的容器:
下列範例會尋找已刪除的容器、取得該已刪除容器的版本標識碼,然後將該標識元傳遞至 undeleteContainer
方法來還原容器。
async function undeleteContainer(blobServiceClient, containerName) {
// Version to restore
let containerVersion;
const containerOptions = {
includeDeleted: true,
prefix: containerName
}
// Find the deleted container and restore it
for await (const containerItem of blobServiceClient.listContainers(containerOptions)) {
if (containerItem.name === containerName) {
containerVersion = containerItem.version;
}
}
const containerClient = await blobServiceClient.undeleteContainer(
containerName,
containerVersion,
);
}
資源
若要深入了解如何使用適用於 JavaScript 的 Azure Blob 儲存體用戶端程式庫刪除容器,請參閱下列資源。
程式碼範例
- 檢視本文中的 JavaScript 和 TypeScript 程式代碼範例 (GitHub)
REST API 操作
適用於 JavaScript 的 Azure SDK 包含建置在 Azure REST API 之上的程式庫,可讓您透過熟悉的 JavaScript 範例與 REST API 作業進行互動。 用來刪除或還原容器的用戶端程式庫方法會使用下列 REST API 作業:
用戶端程式庫資源
另請參閱
相關內容
- 本文是 JavaScript/TypeScript 的 Blob 記憶體開發人員指南的一部分。 若要深入瞭解,請參閱建置 JavaScript/TypeScript 應用程式的完整開發人員指南文章清單。