Azure Logo

Azure Blob Storage Quickstart - Node.js

Overview

This quickstart guides you through uploading, downloading, and managing blobs in Azure Blob Storage using Node.js. Azure Blob Storage is Microsoft's object storage solution for the cloud. Blob storage is optimized to store massive amounts of unstructured data, such as text or binary data.

You'll learn how to:

  • Create a blob container.
  • Upload a blob to a container.
  • Download a blob from a container.
  • List blobs in a container.
  • Delete a blob.

Prerequisites

  • Node.js installed: Download and install from nodejs.org.
  • Azure Subscription: If you don't have one, create a free account before you begin.
  • Azure Storage Account: Create a storage account in the Azure portal.
  • Connection String: Obtain the connection string for your storage account. You can find this in the Azure portal under your storage account's "Access keys" section.

Getting Started with Node.js

Follow these steps to set up your Node.js project and interact with Azure Blob Storage.

  1. Create a project directory:
    mkdir azure-blob-storage-node-quickstart && cd azure-blob-storage-node-quickstart
  2. Initialize a Node.js project:
    npm init -y
  3. Install the Azure Blob Storage SDK for JavaScript:
    npm install @azure/storage-blob
  4. Create a new file named index.js and add the following code:
    // Import necessary modules
    const { BlobServiceClient } = require("@azure/storage-blob");
    const { v1: uuidv1 } = require('uuid'); // For unique blob names
    
    // Replace with your actual connection string and container name
    const connectionString = "";
    const containerName = "quickstartcontainer" + uuidv1().substring(0, 6); // Unique container name
    const blobName = "sample-blob.txt";
    const localFilePath = "./sample-blob.txt"; // Path to your local file
    
    async function main() {
        console.log("Azure Blob Storage - Node.js Quickstart");
    
        // Create a BlobServiceClient object using the connection string
        const blobServiceClient = BlobServiceClient.fromConnectionString(connectionString);
    
        // Get a container client
        const containerClient = blobServiceClient.getContainerClient(containerName);
    
        // Create the container
        try {
            await containerClient.create();
            console.log(`Container "${containerName}" created.`);
        } catch (error) {
            if (error.statusCode === 409) {
                console.log(`Container "${containerName}" already exists.`);
            } else {
                console.error("Error creating container:", error);
                return; // Stop if container creation fails critically
            }
        }
    
        // Create a local file for upload (for demonstration purposes)
        const fs = require('fs');
        fs.writeFileSync(localFilePath, "Hello from Azure Blob Storage Node.js Quickstart!");
        console.log(`Created local file: ${localFilePath}`);
    
        // Upload the blob
        console.log(`Uploading blob "${blobName}" to container "${containerName}"...`);
        const blockBlobClient = containerClient.getBlockBlobClient(blobName);
        await blockBlobClient.uploadFile(localFilePath, {
            onProgress: (progress) => console.log(`Upload progress: ${progress.loadedBytes} bytes`),
        });
        console.log("Blob uploaded successfully.");
    
        // List blobs in the container
        console.log(`Listing blobs in container "${containerName}":`);
        for await (const blobItem of containerClient.listBlobsFlat()) {
            console.log(`- ${blobItem.name}`);
        }
    
        // Download the blob
        const downloadFilePath = `./downloaded-${blobName}`;
        console.log(`Downloading blob "${blobName}" to "${downloadFilePath}"...`);
        await blockBlobClient.downloadToFile(downloadFilePath, 0);
        console.log("Blob downloaded successfully.");
    
        // Delete the blob (optional)
        console.log(`Deleting blob "${blobName}"...`);
        await blockBlobClient.delete();
        console.log("Blob deleted.");
    
        // Delete the container (optional)
        // console.log(`Deleting container "${containerName}"...`);
        // await containerClient.delete();
        // console.log("Container deleted.");
    
        // Clean up local files
        fs.unlinkSync(localFilePath);
        // fs.unlinkSync(downloadFilePath); // Uncomment if you want to clean up downloaded file
        console.log("Local files cleaned up.");
    }
    
    // Helper to replace placeholder
    function replacePlaceholder() {
        if (connectionString === "") {
            console.error("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            console.error("!!! Please replace '' !!!");
            console.error("!!! with your actual Azure Storage connection string.      !!!");
            console.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            process.exit(1);
        }
    }
    
    replacePlaceholder();
    main().catch((err) => {
        console.error("Error running quickstart:", err);
    });
    
  5. Replace placeholders:

    In index.js, replace <YOUR_AZURE_STORAGE_CONNECTION_STRING> with your actual Azure Storage account connection string.

  6. Run the quickstart:
    node index.js