This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
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.
Use the client libraries in this package to:
Key links
See oursupport policy for more details.
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
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
, orBlobClient
for example. Seesamples for creating theBlobServiceClient
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 theREADME for@azure/identity
for more details and samples to get you started.
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.
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.
For more information please refer to ourdocumentation for using Azure SDK for JS in Web Workers
This library depends on following DOM APIs which need external polyfills loaded when used 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".
gzip
ordeflate
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.StorageSharedKeyCredential
generateAccountSASQueryParameters()
generateBlobSASQueryParameters()
BlockBlobClient.uploadData()
is available in both Node.js and browsers.BlockBlobClient.uploadFile()
BlockBlobClient.uploadStream()
BlobClient.downloadToBuffer()
BlobClient.downloadToFile()
BlockBlobClient.uploadBrowserData()
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 ourbundling documentation.
You need to set upCross-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.
Blob storage is designed for:
Blob storage offers three types of resources:
BlobServiceClient
ContainerClient
BlobClient
To use the clients, import the package into your file:
const AzureStorageBlob = require("@azure/storage-blob");
Alternatively, selectively import only the types you need:
const { BlobServiceClient, StorageSharedKeyCredential } = require("@azure/storage-blob");
TheBlobServiceClient
requires an URL to the blob service and an access credential. It also optionally accepts some settings in theoptions
parameter.
DefaultAzureCredential
from@azure/identity
packageRecommended way to instantiate aBlobServiceClient
Setup : Reference - Authorize access to blobs and queues with Azure Active Directory from a client application -https://learn.microsoft.com/azure/storage/common/storage-auth-aad-app
Register a new AAD application and give permissions to access Azure Storage on behalf of the signed-in user
API permissions
section, selectAdd a permission
and chooseMicrosoft APIs
.Azure Storage
and select the checkbox next touser_impersonation
and then clickAdd 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
Access control (IAM)
tab (in the left-side-navbar of your storage account in the azure-portal).Environment setup for the sample
CLIENT ID
andTENANT ID
. In the "Certificates & Secrets" tab, create a secret and note that down.const { DefaultAzureCredential } = require("@azure/identity");const { BlobServiceClient } = require("@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,);
See theAzure AD Auth sample for a complete example using this method.
[Note - Above steps are only for Node.js]
Alternatively, you can instantiate aBlobServiceClient
using thefromConnectionString()
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]
const { BlobServiceClient } = require("@azure/storage-blob");const connStr = "<connection string>";const blobServiceClient = BlobServiceClient.fromConnectionString(connStr);
StorageSharedKeyCredential
Alternatively, you instantiate aBlobServiceClient
with aStorageSharedKeyCredential
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]
const { BlobServiceClient, StorageSharedKeyCredential } = require("@azure/storage-blob");// Enter your storage account name and shared keyconst 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,);
Also, You can instantiate aBlobServiceClient
with a shared access signatures (SAS). You can get the SAS token from the Azure Portal or generate one usinggenerateAccountSASQueryParameters()
.
const { BlobServiceClient } = require("@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}`);
UseBlobServiceClient.getContainerClient()
to get a container client instance then create a new container resource.
const { DefaultAzureCredential } = require("@azure/identity");const { BlobServiceClient } = require("@azure/storage-blob");const account = "<account>";const defaultAzureCredential = new DefaultAzureCredential();const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, defaultAzureCredential,);async function main() { // Create a container const containerName = `newcontainer${new Date().getTime()}`; const containerClient = blobServiceClient.getContainerClient(containerName); const createContainerResponse = await containerClient.create(); console.log(`Create container ${containerName} successfully`, createContainerResponse.requestId);}main();
UseBlobServiceClient.listContainers()
function to iterate the containers,with the newfor-await-of
syntax:
const { DefaultAzureCredential } = require("@azure/identity");const { BlobServiceClient } = require("@azure/storage-blob");const account = "<account>";const defaultAzureCredential = new DefaultAzureCredential();const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, defaultAzureCredential,);async function main() { let i = 1; const containers = blobServiceClient.listContainers(); for await (const container of containers) { console.log(`Container ${i++}: ${container.name}`); }}main();
Alternatively without usingfor-await-of
:
const { DefaultAzureCredential } = require("@azure/identity");const { BlobServiceClient } = require("@azure/storage-blob");const account = "<account>";const defaultAzureCredential = new DefaultAzureCredential();const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, defaultAzureCredential,);async function main() { let i = 1; const iter = blobServiceClient.listContainers(); let containerItem = await iter.next(); while (!containerItem.done) { console.log(`Container ${i++}: ${containerItem.value.name}`); containerItem = await iter.next(); }}main();
In addition, pagination is supported for listing too viabyPage()
:
const { DefaultAzureCredential } = require("@azure/identity");const { BlobServiceClient } = require("@azure/storage-blob");const account = "<account>";const defaultAzureCredential = new DefaultAzureCredential();const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, defaultAzureCredential,);async function main() { let i = 1; for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { if (response.containerItems) { for (const container of response.containerItems) { console.log(`Container ${i++}: ${container.name}`); } } }}main();
For a complete sample on iterating containers please seesamples/v12/typescript/src/listContainers.ts.
const { DefaultAzureCredential } = require("@azure/identity");const { BlobServiceClient } = require("@azure/storage-blob");const account = "<account>";const defaultAzureCredential = new DefaultAzureCredential();const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, defaultAzureCredential,);const containerName = "<container name>";async function main() { const containerClient = blobServiceClient.getContainerClient(containerName); const content = "Hello world!"; const blobName = "newblob" + new Date().getTime(); const blockBlobClient = containerClient.getBlockBlobClient(blobName); const uploadBlobResponse = await blockBlobClient.upload(content, content.length); console.log(`Upload block blob ${blobName} successfully`, uploadBlobResponse.requestId);}main();
Similar to listing containers.
const { DefaultAzureCredential } = require("@azure/identity");const { BlobServiceClient } = require("@azure/storage-blob");const account = "<account>";const defaultAzureCredential = new DefaultAzureCredential();const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, defaultAzureCredential,);const containerName = "<container name>";async function main() { const containerClient = blobServiceClient.getContainerClient(containerName); let i = 1; const blobs = containerClient.listBlobsFlat(); for await (const blob of blobs) { console.log(`Blob ${i++}: ${blob.name}`); }}main();
For a complete sample on iterating blobs please seesamples/v12/typescript/src/listBlobsFlat.ts.
const { DefaultAzureCredential } = require("@azure/identity");const { BlobServiceClient } = require("@azure/storage-blob");const account = "<account>";const defaultAzureCredential = new DefaultAzureCredential();const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, defaultAzureCredential,);const containerName = "<container name>";const blobName = "<blob name>";async function main() { 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.readableStreamBody const downloadBlockBlobResponse = await blobClient.download(); const downloaded = ( await streamToBuffer(downloadBlockBlobResponse.readableStreamBody) ).toString(); console.log("Downloaded blob content:", downloaded); // [Node.js only] A helper method used to read a Node.js readable stream into a Buffer async function streamToBuffer(readableStream) { return new Promise((resolve, reject) => { const chunks = []; readableStream.on("data", (data) => { chunks.push(typeof data === "string" ? Buffer.from(data) : data); }); readableStream.on("end", () => { resolve(Buffer.concat(chunks)); }); readableStream.on("error", reject); }); }}main();
Please refer to theJavaScript Bundle section for more information on using this library in the browser.
const { BlobServiceClient } = require("@azure/storage-blob");const account = "<account name>";const sas = "<service Shared Access Signature Token>";const containerName = "<container name>";const blobName = "<blob name>";const blobServiceClient = new BlobServiceClient(`https://${account}.blob.core.windows.net?${sas}`);async function main() { 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.blobBody const downloadBlockBlobResponse = await blobClient.download(); const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody); console.log("Downloaded blob content", downloaded); // [Browsers only] A helper method used to convert a browser Blob into string. async function blobToString(blob) { const fileReader = new FileReader(); return new Promise((resolve, reject) => { fileReader.onloadend = (ev) => { resolve(ev.target.result); }; fileReader.onerror = reject; fileReader.readAsText(blob); }); }}main();
A complete example of simple scenarios is atsamples/v12/typescript/src/sharedKeyAuth.ts.
Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set theAZURE_LOG_LEVEL
environment variable toinfo
. Alternatively, logging can be enabled at runtime by callingsetLogLevel
in the@azure/logger
:
const { setLogLevel } = require("@azure/logger");setLogLevel("info");
More code samples:
If you'd like to contribute to this library, please read thecontributing guide to learn more about how to build and test the code.
Also refer toStorage specific guide for additional information on setting up the test environment for storage libraries.
Was this page helpful?
Was this page helpful?