A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://learn.microsoft.com/en-us/javascript/api/overview/azure/storage-blob-readme below:

Azure Storage Blob client library for JavaScript

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

Getting started Currently supported environments

See our support policy for more details.

Prerequisites Install the package

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.

Azure Active Directory

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.

For more information please refer to our documentation 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:

Differences between Node.js and browsers

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".

Features, interfaces, classes or functions only available in Node.js Features, interfaces, classes or functions only available in browsers 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.

Key concepts

Blob storage is designed for:

Blob storage offers three types of resources:

Examples Import the package

To use the clients, import the package into your file:

import * as AzureStorageBlob from "@azure/storage-blob";

Alternatively, selectively import only the types you need:

import { BlobServiceClient, StorageSharedKeyCredential } from "@azure/storage-blob";
Create the blob service client

The BlobServiceClient requires an URL to the blob service and an access credential. It also optionally accepts some settings in the options parameter.

with DefaultAzureCredential from @azure/identity package

Recommended way to instantiate a BlobServiceClient

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

import { DefaultAzureCredential } from "@azure/identity";
import { BlobServiceClient } from "@azure/storage-blob";

// Enter your storage account name
const account = "<account>";
const defaultAzureCredential = new DefaultAzureCredential();

const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  defaultAzureCredential,
);

See the Azure AD Auth sample for a complete example using this method.

[Note - Above steps are only for Node.js]

using connection string

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]

import { BlobServiceClient } from "@azure/storage-blob";

const connStr = "<connection string>";

const blobServiceClient = BlobServiceClient.fromConnectionString(connStr);

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 browsers
const 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 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);
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}`);
  }
}

For a complete sample on iterating containers please see samples/v12/typescript/src/listContainers.ts.

Create a blob by uploading data
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 containerClient = blobServiceClient.getContainerClient(containerName);

const content = "Hello world!";
const blobName = `newblob ${+new Date()}`;
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
const uploadBlobResponse = await blockBlobClient.upload(content, content.length);
console.log(
  `Upload block blob ${blobName} successfully with request ID: ${uploadBlobResponse.requestId}`,
);
List blobs inside a container

Similar to listing containers.

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 containerClient = blobServiceClient.getContainerClient(containerName);

let i = 1;
const blobs = containerClient.listBlobsFlat();
for await (const blob of blobs) {
  console.log(`Blob ${i++}: ${blob.name}`);
}

For a complete sample on iterating blobs please see samples/v12/typescript/src/listBlobsFlat.ts.

Download a blob and convert it to a string (Node.js)
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 Node.js, get downloaded data by accessing downloadBlockBlobResponse.readableStreamBody
const downloadBlockBlobResponse = await blobClient.download();
if (downloadBlockBlobResponse.readableStreamBody) {
  const downloaded = await streamToString(downloadBlockBlobResponse.readableStreamBody);
  console.log(`Downloaded blob content: ${downloaded}`);
}

async function streamToString(stream: NodeJS.ReadableStream): Promise<string> {
  const result = await new Promise<Buffer<ArrayBuffer>>((resolve, reject) => {
    const chunks: Buffer[] = [];
    stream.on("data", (data) => {
      chunks.push(Buffer.isBuffer(data) ? data : Buffer.from(data));
    });
    stream.on("end", () => {
      resolve(Buffer.concat(chunks));
    });
    stream.on("error", reject);
  });
  return result.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.blobBody
const downloadBlockBlobResponse = await blobClient.download();
const blobBody = await downloadBlockBlobResponse.blobBody;
if (blobBody) {
  const downloaded = await blobBody.text();
  console.log(`Downloaded blob content: ${downloaded}`);
}

A complete example of simple scenarios is at samples/v12/typescript/src/sharedKeyAuth.ts.

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");
Next steps

More code samples:

Contributing

If you'd like to contribute to this library, please read the contributing guide to learn more about how to build and test the code.

Also refer to Storage specific guide for additional information on setting up the test environment for storage libraries.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4