Getting Started with Azure Blob Storage using the JavaScript SDK
This guide will walk you through the essential steps to start using the Azure Blob Storage SDK for JavaScript. Blob storage is a cost-effective and highly scalable cloud object storage solution for unstructured data like images, videos, documents, and backups.
1. Prerequisites
- An Azure Subscription. If you don't have one, create a free account.
- An Azure Storage Account. You can create one in the Azure portal.
- Node.js and npm installed on your machine.
2. Installation
Install the necessary Azure Blob Storage SDK package using npm:
npm install @azure/storage-blob
3. Authentication
You can authenticate to Azure Blob Storage using a connection string or Shared Access Signatures (SAS). For simplicity in this guide, we'll use a connection string.
Retrieve your storage account connection string from the Azure portal under your storage account's "Access keys" section.
4. Basic Operations
Here's a simple JavaScript example demonstrating how to create a blob container and upload a text file.
Example: Uploading a Blob
Create a new JavaScript file (e.g., uploadBlob.js) and add the following code:
// Import the BlobServiceClient
import { BlobServiceClient } from "@azure/storage-blob";
// --- Configuration ---
const connectionString = ""; // Replace with your connection string
const containerName = "my-javascript-container"; // Choose a name for your container
const blobName = "my-text-blob.txt"; // Name for your blob
const blobContent = "Hello, Azure Blob Storage from JavaScript SDK!"; // Content to upload
// --- End Configuration ---
async function main() {
console.log("Azure Blob Storage - JavaScript SDK Example");
// Create a BlobServiceClient object using the connection string
const blobServiceClient = BlobServiceClient.fromConnectionString(connectionString);
// Get a container client from the service client
const containerClient = blobServiceClient.getContainerClient(containerName);
// Create the container if it doesn't exist
try {
await containerClient.createIfNotExists();
console.log(`Container "${containerName}" created or already exists.`);
} catch (error) {
console.error("Error creating container:", error);
return; // Exit if container creation fails
}
// Get a blob client
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
// Upload the blob
try {
const uploadBlobResponse = await blockBlobClient.upload(blobContent, blobContent.length);
console.log(`Blob "${blobName}" uploaded successfully. ETag: ${uploadBlobResponse.eTag}`);
} catch (error) {
console.error("Error uploading blob:", error);
}
// Optional: List blobs in the container
console.log("\nListing blobs in container:");
for await (const blobItem of containerClient.listBlobs()) {
console.log("- ", blobItem.name);
}
}
main().catch((err) => {
console.error("The example encountered an error:", err.message);
});
Running the Example
- Replace
<YOUR_AZURE_STORAGE_CONNECTION_STRING>with your actual Azure Storage Account connection string. - Save the code as
uploadBlob.js. - Ensure your project is set up to use ES modules (e.g., by adding
"type": "module"to yourpackage.jsonor using a transpiler like Babel). - Run the script from your terminal:
node uploadBlob.js
Next Steps
- Explore other blob operations like downloading blobs, deleting blobs, and managing container properties.
- Learn about different blob types (block blobs, append blobs, page blobs).
- Implement more robust error handling and logging.
- Secure your application by using Azure Key Vault or managed identities for credentials.
For more detailed information and advanced scenarios, please refer to the official Azure Blob Storage documentation and the Azure Blob Storage SDK for JavaScript GitHub repository.