Azure Storage Blob is Microsoft's object storage solution for the cloud. Blob storage is optimized for storing massive amounts of unstructured data. Unstructured data is data that does not adhere to a particular data model or definition, such as text or binary data.
This project provides a client library in JavaScript that makes it easy to consume Microsoft Azure Storage Blob service.
The preferred way to install the Azure Storage Blob client library for JavaScript is to use the npm package manager. Type the following into a terminal window:
npm install @azure/storage-blob
Authenticate the client
Azure Storage supports several ways to authenticate. In order to interact with the Azure Blob Storage service you'll need to create an instance of a Storage client - BlobServiceClient, ContainerClient, or BlobClient for example. See samples for creating the BlobServiceClient to learn more about authentication.
The Azure Blob Storage service supports the use of Azure Active Directory to authenticate requests to its APIs. The @azure/identity package provides a variety of credential types that your application can use to do this. Please see the README for @azure/identity for more details and samples to get you started.
Compatibility
This library is compatible with Node.js and browsers, and validated against LTS Node.js versions (>=8.16.0) and latest versions of Chrome, Firefox and Edge.
Web Workers
This library requires certain DOM objects to be globally available when used in the browser, which web workers do not make available by default. You will need to polyfill these to make this library work in web workers.
There are differences between Node.js and browsers runtime. When getting started with this library, pay attention to APIs or classes marked with "ONLY AVAILABLE IN NODE.JS RUNTIME" or "ONLY AVAILABLE IN BROWSERS".
If a blob holds compressed data in gzip or deflate format and its content encoding is set accordingly, downloading behavior is different between Node.js and browsers. In Node.js storage clients will download the blob in its compressed format, while in browsers the data will be downloaded in de-compressed format.
Features, interfaces, classes or functions only available in Node.js
Shared Key Authorization based on account name and account key
StorageSharedKeyCredential
Shared Access Signature(SAS) generation
generateAccountSASQueryParameters()
generateBlobSASQueryParameters()
Parallel uploading and downloading. Note that BlockBlobClient.uploadData() is available in both Node.js and browsers.
BlockBlobClient.uploadFile()
BlockBlobClient.uploadStream()
BlobClient.downloadToBuffer()
BlobClient.downloadToFile()
Features, interfaces, classes or functions only available in browsers
Parallel uploading and downloading
BlockBlobClient.uploadBrowserData()
JavaScript Bundle
To use this client library in the browser, first you need to use a bundler. For details on how to do this, please refer to our bundling documentation.
CORS
You need to set up Cross-Origin Resource Sharing (CORS) rules for your storage account if you need to develop for browsers. Go to Azure portal and Azure Storage Explorer, find your storage account, create new CORS rules for blob/queue/file/table service(s).
For example, you can create following CORS settings for debugging. But please customize the settings carefully according to your requirements in production environment.
In the API permissions section, select Add a permission and choose Microsoft APIs.
Pick Azure Storage and select the checkbox next to user_impersonation and then click Add permissions. This would allow the application to access Azure Storage on behalf of the signed-in user.
Grant access to Azure Blob data with RBAC in the Azure Portal
In the azure portal, go to your storage-account and assign Storage Blob Data Contributor role to the registered AAD application from Access control (IAM) tab (in the left-side-navbar of your storage account in the azure-portal).
Environment setup for the sample
From the overview page of your AAD Application, note down the CLIENT ID and TENANT ID. In the "Certificates & Secrets" tab, create a secret and note that down.
Make sure you have AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET as environment variables to successfully execute the sample(Can leverage process.env).
import { DefaultAzureCredential } from "@azure/identity";import { BlobServiceClient } from "@azure/storage-blob";// Enter your storage account nameconst account = "<account>";const defaultAzureCredential = new DefaultAzureCredential();const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, defaultAzureCredential,);
Alternatively, you can instantiate a BlobServiceClient using the fromConnectionString() static method with the full connection string as the argument. (The connection string can be obtained from the azure portal.) [ONLY AVAILABLE IN NODE.JS RUNTIME]
Alternatively, you instantiate a BlobServiceClient with a StorageSharedKeyCredential by passing account-name and account-key as arguments. (The account-name and account-key can be obtained from the azure portal.)
[ONLY AVAILABLE IN NODE.JS RUNTIME]
import { StorageSharedKeyCredential, BlobServiceClient } from "@azure/storage-blob";const account = "<account>";const accountKey = "<accountkey>";// Use StorageSharedKeyCredential with storage account and account key// StorageSharedKeyCredential is only available in Node.js runtime, not in browsersconst sharedKeyCredential = new StorageSharedKeyCredential(account, accountKey);const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, sharedKeyCredential,);
with SAS Token
Also, You can instantiate a BlobServiceClient with a shared access signatures (SAS). You can get the SAS token from the Azure Portal or generate one using generateAccountSASQueryParameters().
import { BlobServiceClient } from "@azure/storage-blob";const account = "<account name>";const sas = "<service Shared Access Signature Token>";const blobServiceClient = new BlobServiceClient(`https://${account}.blob.core.windows.net?${sas}`);
Create a new container
Use BlobServiceClient.getContainerClient() to get a container client instance then create a new container resource.
import { BlobServiceClient } from "@azure/storage-blob";import { DefaultAzureCredential } from "@azure/identity";const account = "<account>";const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, new DefaultAzureCredential(),);// Create a containerconst containerName = `newcontainer${new Date().getTime()}`;const containerClient = blobServiceClient.getContainerClient(containerName);const createContainerResponse = await containerClient.create();console.log(`Create container ${containerName} successfully`, createContainerResponse.requestId);
List the containers
Use BlobServiceClient.listContainers() function to iterate the containers,
with the new for-await-of syntax:
import { BlobServiceClient } from "@azure/storage-blob";import { DefaultAzureCredential } from "@azure/identity";const account = "<account>";const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, new DefaultAzureCredential(),);let i = 1;const containers = blobServiceClient.listContainers();for await (const container of containers) { console.log(`Container ${i++}: ${container.name}`);}
Alternatively without using for-await-of:
import { BlobServiceClient } from "@azure/storage-blob";import { DefaultAzureCredential } from "@azure/identity";const account = "<account>";const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, new DefaultAzureCredential(),);let i = 1;const iter = blobServiceClient.listContainers();let { value, done } = await iter.next();while (!done) { console.log(`Container ${i++}: ${value.name}`); ({ value, done } = await iter.next());}
In addition, pagination is supported for listing too via byPage():
import { BlobServiceClient } from "@azure/storage-blob";import { DefaultAzureCredential } from "@azure/identity";const account = "<account>";const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, new DefaultAzureCredential(),);let i = 1;for await (const page of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { for (const container of page.containerItems) { console.log(`Container ${i++}: ${container.name}`); }}
listBlobsFlat and listBlobsByHierarchy use the Apache Arrow response format by default; set responseFormat to choose it explicitly, or set it to StorageResponseFormat.Xml to request XML. The service falls back to XML for accounts that don't support Apache Arrow, and the parsed blob items are identical either way.
import { BlobServiceClient, StorageResponseFormat } from "@azure/storage-blob";import { DefaultAzureCredential } from "@azure/identity";const account = "<account>";const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, new DefaultAzureCredential(),);const containerName = "<container name>";const containerClient = blobServiceClient.getContainerClient(containerName);// Request the listing as Apache Arrow. The service falls back to XML for accounts// that don't support Apache Arrow; the parsed blob items are identical either way.let i = 1;const blobs = containerClient.listBlobsFlat({ responseFormat: StorageResponseFormat.Arrow,});for await (const blob of blobs) { console.log(`Blob ${i++}: ${blob.name}`);}
Download a blob and convert it to a string (Node.js)
import { BlobServiceClient } from "@azure/storage-blob";import { DefaultAzureCredential } from "@azure/identity";import { buffer } from "node:stream/consumers";const account = "<account>";const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, new DefaultAzureCredential(),);const containerName = "<container name>";const blobName = "<blob name>";const containerClient = blobServiceClient.getContainerClient(containerName);const blobClient = containerClient.getBlobClient(blobName);// Get blob content from position 0 to the end// In Node.js, get downloaded data by accessing downloadBlockBlobResponse.readableStreamBodyconst downloadBlockBlobResponse = await blobClient.download();if (downloadBlockBlobResponse.readableStreamBody) { // Download the raw bytes of the blob. Use `text` from "node:stream/consumers" // instead if you want to read the content as a string directly. const downloaded = await buffer(downloadBlockBlobResponse.readableStreamBody); console.log(`Downloaded blob content: ${downloaded.toString()}`);}
Download a blob and convert it to a string (Browsers).
Please refer to the JavaScript Bundle section for more information on using this library in the browser.
import { BlobServiceClient } from "@azure/storage-blob";import { DefaultAzureCredential } from "@azure/identity";const account = "<account>";const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, new DefaultAzureCredential(),);const containerName = "<container name>";const blobName = "<blob name>";const containerClient = blobServiceClient.getContainerClient(containerName);const blobClient = containerClient.getBlobClient(blobName);// Get blob content from position 0 to the end// In browsers, get downloaded data by accessing downloadBlockBlobResponse.blobBodyconst downloadBlockBlobResponse = await blobClient.download();const blobBody = await downloadBlockBlobResponse.blobBody;if (blobBody) { const downloaded = await blobBody.text(); console.log(`Downloaded blob content: ${downloaded}`);}
Authenticate downloads with a session token (Node.js)
When you authenticate with a TokenCredential, you can opt in to session token authentication. Eligible blob downloads are then signed with a container-scoped session token instead of a bearer token, which avoids a token exchange on every request.
Sessions are disabled by default. Set sessionOptions.mode to "enabled" to opt in.
[ONLY AVAILABLE IN NODE.JS RUNTIME]
Only GET blob download requests are eligible; container and service operations, and any request using a structured message body, continue to use a bearer token. If a session cannot be created because the account does not have the feature enabled, the client logs a warning and falls back to bearer tokens rather than failing the download.
In browsers and React Native, sessionOptions is accepted for type compatibility but has no effect, because signing a session requires Shared Key, which is unavailable outside Node.js.
import { BlobServiceClient } from "@azure/storage-blob";import { DefaultAzureCredential } from "@azure/identity";import { buffer } from "node:stream/consumers";const account = "<account>";// Session token authentication is only available in the Node.js runtime. In browsers and// React Native these options are ignored and requests keep using a bearer token.const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, new DefaultAzureCredential(), { sessionOptions: { mode: "enabled" } },);// Only the download below is signed with a container-scoped session token. Container and// service operations continue to use a bearer token.const containerClient = blobServiceClient.getContainerClient("<container name>");const blobClient = containerClient.getBlobClient("<blob name>");const downloadBlockBlobResponse = await blobClient.download();if (downloadBlockBlobResponse.readableStreamBody) { const downloaded = await buffer(downloadBlockBlobResponse.readableStreamBody); console.log(`Downloaded blob content: ${downloaded.toString()}`);}
If your endpoint URL is not in the standard https://<account>.blob.core.windows.net form, the account name cannot be derived from it. Set sessionOptions.accountName explicitly in that case.
Read blobs from the endpoints that store them (Node.js)
The service can describe a blob's layout: which storage endpoint holds each range of the blob. When the first block that downloadToBuffer reads comes back with a hint that the blob has a layout, the client can fetch the layout and read the remaining blocks directly from those endpoints, rather than having the account endpoint relay them. This is off by default; set layoutAwareRouting to "enabled" to opt in. The requests stay authenticated as, and addressed to, your account. When the account doesn't support it, the blob is read from the account endpoint as usual.
[ONLY AVAILABLE IN NODE.JS RUNTIME]
import { BlobServiceClient } from "@azure/storage-blob";import { DefaultAzureCredential } from "@azure/identity";const account = "<account>";const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, new DefaultAzureCredential(),);const containerClient = blobServiceClient.getContainerClient("<container name>");const blobClient = containerClient.getBlobClient("<blob name>");// Routing is off by default. Opt in to read blocks from the endpoints that hold them.const downloaded = await blobClient.downloadToBuffer(0, undefined, { layoutAwareRouting: "enabled",});console.log(`Downloaded ${downloaded.length} bytes`);
Troubleshooting
Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the AZURE_LOG_LEVEL environment variable to info. Alternatively, logging can be enabled at runtime by calling setLogLevel in the @azure/logger:
import { setLogLevel } from "@azure/logger";setLogLevel("info");