Quickstart: Manage blobs with JavaScript v12 SDK in Node.js

In this quickstart, you learn to manage blobs by using Node.js. Blobs are objects that can hold large amounts of text or binary data, including images, documents, streaming media, and archive data.

These example code snippets show you how to perform the following with the Azure Blob storage package library for JavaScript:

Additional resources:

API reference | Library source code | Package (npm) | Samples

Prerequisites

Object model

Azure Blob storage is optimized for storing massive amounts of unstructured data. Unstructured data is data that doesn't adhere to a particular data model or definition, such as text or binary data. Blob storage offers three types of resources:

  • The storage account
  • A container in the storage account
  • A blob in the container

The following diagram shows the relationship between these resources.

Diagram of Blob storage architecture

Use the following JavaScript classes to interact with these resources:

  • BlobServiceClient: The BlobServiceClient class allows you to manipulate Azure Storage resources and blob containers.
  • ContainerClient: The ContainerClient class allows you to manipulate Azure Storage containers and their blobs.
  • BlobClient: The BlobClient class allows you to manipulate Azure Storage blobs.

Create the Node.js project

Create a JavaScript application named blob-quickstart-v12.

  1. In a console window (such as cmd, PowerShell, or Bash), create a new directory for the project.

    mkdir blob-quickstart-v12
    
  2. Switch to the newly created blob-quickstart-v12 directory.

    cd blob-quickstart-v12
    
  3. Create a package.json.

    npm init -y
    
  4. Open the project in Visual Studio Code:

    code .
    

Install the npm package for blob storage

  1. Install the Azure Storage npm package:

    npm install @azure/storage-blob
    
  2. Install other dependencies used in this quickstart:

    npm install uuid dotenv
    

Create JavaScript file

From the project directory:

  1. Create a new file named index.js.

  2. Copy the following code into the file. More code will be added as you go through this quickstart.

    const { BlobServiceClient } = require('@azure/storage-blob');
    const { v1: uuidv1} = require('uuid');
    require('dotenv').config()
    
    async function main() {
        console.log('Azure Blob storage v12 - JavaScript quickstart sample');
    
        // Quick start code goes here
    
    }
    
    main()
    .then(() => console.log('Done'))
    .catch((ex) => console.log(ex.message));
    

Copy your credentials from the Azure portal

When the sample application makes a request to Azure Storage, it must be authorized. To authorize a request, add your storage account credentials to the application as a connection string. To view your storage account credentials, follow these steps:

  1. Sign in to the Azure portal.

  2. Locate your storage account.

  3. In the storage account menu pane, under Security + networking, select Access keys. Here, you can view the account access keys and the complete connection string for each key.

    Screenshot that shows where the access key settings are in the Azure portal

  4. In the Access keys pane, select Show keys.

  5. In the key1 section, locate the Connection string value. Select the Copy to clipboard icon to copy the connection string. You'll add the connection string value to an environment variable in the next section.

    Screenshot showing how to copy a connection string from the Azure portal

Configure your storage connection string

After you copy the connection string, write it to a new environment variable on the local machine running the application. To set the environment variable, open a console window, and follow the instructions for your operating system. Replace <yourconnectionstring> with your actual connection string.

setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"

After you add the environment variable in Windows, you must start a new instance of the command window.

Restart programs

After you add the environment variable, restart any running programs that will need to read the environment variable. For example, restart your development environment or editor before you continue.

Get the connection string

The code below retrieves the connection string for the storage account from the environment variable created in the Configure your storage connection string section.

Add this code inside the main function:

const AZURE_STORAGE_CONNECTION_STRING =
  process.env.AZURE_STORAGE_CONNECTION_STRING;

if (!AZURE_STORAGE_CONNECTION_STRING) {
  throw Error("Azure Storage Connection string not found");
}

Create a container

  1. Decide on a name for the new container. Container names must be lowercase.

    For more information about naming containers and blobs, see Naming and Referencing Containers, Blobs, and Metadata.

  2. Add this code to the end of the main function:

    // Create the BlobServiceClient object which will be used to create a container client
    const blobServiceClient = BlobServiceClient.fromConnectionString(
      AZURE_STORAGE_CONNECTION_STRING
    );
    
    // Create a unique name for the container
    const containerName = "quickstart" + uuidv1();
    
    console.log("\nCreating container...");
    console.log("\t", containerName);
    
    // Get a reference to a container
    const containerClient = blobServiceClient.getContainerClient(containerName);
    // Create the container
    const createContainerResponse = await containerClient.create();
    console.log(
      "Container was created successfully. requestId: ",
      createContainerResponse.requestId
    );
    

    The preceding code creates an instance of the BlobServiceClient class by calling the fromConnectionString method. Then, call the getContainerClient method to get a reference to a container. Finally, call create to actually create the container in your storage account.

Upload blobs to a container

Copy the following code to the end of the main function to upload a text string to a blob:

// Create a unique name for the blob
const blobName = "quickstart" + uuidv1() + ".txt";

// Get a block blob client
const blockBlobClient = containerClient.getBlockBlobClient(blobName);

console.log("\nUploading to Azure storage as blob:\n\t", blobName);

// Upload data to the blob
const data = "Hello, World!";
const uploadBlobResponse = await blockBlobClient.upload(data, data.length);
console.log(
  "Blob was uploaded successfully. requestId: ",
  uploadBlobResponse.requestId
);

The preceding code gets a reference to a BlockBlobClient object by calling the getBlockBlobClient method on the ContainerClient from the Create a container section. The code uploads the text string data to the blob by calling the upload method.

List the blobs in a container

Add the following code to the end of the main function to list the blobs in the container.

console.log("\nListing blobs...");

// List the blob(s) in the container.
for await (const blob of containerClient.listBlobsFlat()) {
  console.log("\t", blob.name);
}

The preceding code calls the listBlobsFlat method. In this case, only one blob has been added to the container, so the listing operation returns just that one blob.

Download blobs

  1. Add the following code to the end of the main function to download the previously created blob into the app runtime.

    // Get blob content from position 0 to the end
    // In Node.js, get downloaded data by accessing downloadBlockBlobResponse.readableStreamBody
    // In browsers, get downloaded data by accessing downloadBlockBlobResponse.blobBody
    const downloadBlockBlobResponse = await blockBlobClient.download(0);
    console.log("\nDownloaded blob content...");
    console.log(
      "\t",
      await streamToText(downloadBlockBlobResponse.readableStreamBody)
    );
    

    The preceding code calls the download method.

  2. Copy the following code after the main function to convert a stream back into a string.

    // Convert stream to text
    async function streamToText(readable) {
      readable.setEncoding('utf8');
      let data = '';
      for await (const chunk of readable) {
        data += chunk;
      }
      return data;
    }
    

Delete a container

Add this code to the end of the main function to delete the container and all its blobs:

// Delete container
console.log("\nDeleting container...");

const deleteContainerResponse = await containerClient.delete();
console.log(
  "Container was deleted successfully. requestId: ",
  deleteContainerResponse.requestId
);

The preceding code cleans up the resources the app created by removing the entire container using the ​delete method. You can also delete the local files, if you like.

Run the code

  1. From a Visual Studio Code terminal, run the app.

    node index.js
    
  2. The output of the app is similar to the following example:

    Azure Blob storage v12 - JavaScript quickstart sample
    
    Creating container...
             quickstart4a0780c0-fb72-11e9-b7b9-b387d3c488da
    
    Uploading to Azure Storage as blob:
             quickstart4a3128d0-fb72-11e9-b7b9-b387d3c488da.txt
    
    Listing blobs...
             quickstart4a3128d0-fb72-11e9-b7b9-b387d3c488da.txt
    
    Downloaded blob content...
             Hello, World!
    
    Deleting container...
    Done
    

Step through the code in your debugger and check your Azure portal throughout the process. Check to see that the container is being created. You can open the blob inside the container and view the contents.

Use the storage emulator

This quickstart created a container and blob on the Azure cloud. You can also use the Azure Blob storage npm package to create these resources locally on the Azure Storage emulator for development and testing.

Clean up

  1. When you're done with this quickstart, delete the blob-quickstart-v12 directory.
  2. If you're done using your Azure Storage resource, use the Azure CLI to remove the Storage resource.

Next steps

In this quickstart, you learned how to upload, download, and list blobs using JavaScript.

For tutorials, samples, quickstarts, and other documentation, visit: