次の方法で共有


JavaScript 用の Azure Storage BLOB クライアント ライブラリ - バージョン 12.28.0

Azure Storage BLOB は、クラウド用の Microsoft のオブジェクト ストレージ ソリューションです。 BLOB ストレージは、大量の非構造化データを格納するために最適化されています。 非構造化データとは、テキストやバイナリ データなど、特定のデータ モデルや定義に準拠していないデータです。

このプロジェクトは、Microsoft Azure Storage Blob Service を簡単に使用できる JavaScript のクライアント ライブラリを提供します。

このパッケージのクライアント ライブラリを使用して、次の操作を行います。

  • Blob Service プロパティの取得/設定
  • Create/List/Delete Containers
  • ブロック BLOB の作成、読み取り、一覧表示、更新、削除
  • ページ BLOB の作成、読み取り、一覧表示、更新、削除
  • 追加 BLOB の作成、読み取り、一覧表示、更新、削除

Key links

Getting started

現在サポートされている環境

  • Node.js の LTS バージョンを する
  • Safari、Chrome、Edge、Firefox の最新バージョン。

See our support policy for more details.

Prerequisites

パッケージをインストールする

JavaScript 用の Azure Storage BLOB クライアント ライブラリをインストールする場合は、npm パッケージ マネージャーを使用することをお勧めします。 ターミナル ウィンドウに次のように入力します。

npm install @azure/storage-blob

クライアントを認証する

Azure Storage では、いくつかの認証方法がサポートされています。 Azure Blob Storage サービスと対話するには、ストレージ クライアントのインスタンス (BlobServiceClientContainerClientBlobClient など) を作成する必要があります。 認証の詳細については、 の作成に関する サンプルを参照してください。

Azure Active Directory

Azure Blob Storage サービスでは、Azure Active Directory を使用して API への要求を認証できます。 @azure/identity パッケージには、アプリケーションでこれを行うために使用できるさまざまな資格情報の種類が用意されています。 作業を開始するための詳細とサンプルについては、README を参照してください。

Compatibility

このライブラリは、Node.js とブラウザーと互換性があり、LTS Node.js バージョン (>=8.16.0) と Chrome、Firefox、Edge の最新バージョンに対して検証されます。

Web Workers

このライブラリでは、ブラウザーで使用する場合、特定の DOM オブジェクトをグローバルに使用できる必要があります。Web ワーカーは既定では使用できません。 Web ワーカーでこのライブラリを動作させるには、これらをポリフィルする必要があります。

詳細については、Web Worker で Azure SDK for JS を使用するための ドキュメントを参照してください

このライブラリは、Web ワーカーで使用するときに外部ポリフィルを読み込む必要がある次の DOM API に依存します。

Node.js とブラウザーの違い

Node.js とブラウザーのランタイムには違いがあります。 このライブラリの使用を開始するときは、"ONLY AVAILABLE IN NODE.JS RUNTIME" または "ONLY AVAILABLE IN BROWSERS"でマークされた API またはクラスに注意してください。

  • BLOB が圧縮されたデータを gzip または deflate 形式で保持し、それに応じてコンテンツ エンコードが設定されている場合、ダウンロード動作は Node.js とブラウザーで異なります。 Node.js ストレージ クライアントでは、BLOB は圧縮形式でダウンロードされますが、ブラウザーではデータは圧縮解除形式でダウンロードされます。
Node.js でのみ使用できる機能、インターフェイス、クラス、または関数
  • アカウント名とアカウント キーに基づく共有キーの承認
    • StorageSharedKeyCredential
  • Shared Access Signature (SAS) の生成
    • generateAccountSASQueryParameters()
    • generateBlobSASQueryParameters()
  • 並列アップロードとダウンロード。 BlockBlobClient.uploadData() は、Node.js とブラウザーの両方で使用できます。
    • BlockBlobClient.uploadFile()
    • BlockBlobClient.uploadStream()
    • BlobClient.downloadToBuffer()
    • BlobClient.downloadToFile()
ブラウザーでのみ使用できる機能、インターフェイス、クラス、または関数
  • 並列アップロードとダウンロード
    • BlockBlobClient.uploadBrowserData()

JavaScript Bundle

ブラウザーでこのクライアント ライブラリを使用するには、まず、バンドルを使用する必要があります。 For details on how to do this, please refer to our bundling documentation.

CORS

ブラウザー用に開発する必要がある場合は、ストレージ アカウント クロスオリジン リソース共有 (CORS) 規則を設定する必要があります。 Azure portal と Azure Storage Explorer に移動し、ストレージ アカウントを見つけ、BLOB/キュー/ファイル/テーブル サービス用の新しい CORS ルールを作成します。

たとえば、デバッグ用に次の CORS 設定を作成できます。 ただし、運用環境の要件に合わせて設定を慎重にカスタマイズしてください。

  • 許可される配信元: *
  • 使用できる動詞: DELETE、GET、HEAD、MERGE、POST、OPTIONS、PUT
  • 許可されるヘッダー: *
  • 公開されたヘッダー: *
  • 最長有効期間 (秒): 86400

Key concepts

BLOB ストレージは、次の目的で設計されています。

  • イメージまたはドキュメントをブラウザーに直接提供する。
  • 分散アクセス用のファイルの格納。
  • ストリーミング ビデオとオーディオ。
  • ログ ファイルへの書き込み。
  • バックアップと復元、ディザスター リカバリー、アーカイブ用のデータを格納する。
  • オンプレミスまたは Azure でホストされるサービスによる分析用のデータの格納。

Blob Storage には、次の 3 種類のリソースが用意されています。

  • The storage account used via BlobServiceClient
  • A container in the storage account used via ContainerClient
  • A blob in a container used via BlobClient

Examples

パッケージをインポートする

クライアントを使用するには、パッケージをファイルにインポートします。

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

または、必要な型のみを選択的にインポートします。

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

BLOB サービス クライアントを作成する

BlobServiceClient には、BLOB サービスへの URL とアクセス資格情報が必要です。 また、必要に応じて、options パラメーターの一部の設定を受け入れます。

パッケージからの DefaultAzureCredential@azure/identity 使用

BlobServiceClient をインスタンス化するための推奨される方法

セットアップ : リファレンス - クライアント アプリケーションから Azure Active Directory を使用して BLOB とキューへのアクセスを承認する - https://learn.microsoft.com/azure/storage/common/storage-auth-aad-app

  • 新しい AAD アプリケーションを登録し、サインインしているユーザーの代わりに Azure Storage にアクセスするためのアクセス許可を付与する

    • Azure Active Directory(azure-portal)に新しいアプリケーションを登録する - https://learn.microsoft.com/azure/active-directory/develop/quickstart-register-app
    • [API permissions] セクションで、[Add a permission] を選択し、[Microsoft APIs] を選択します。
    • Azure Storage を選択し、[user_impersonation] の横にあるチェックボックスをオンにして、[Add permissions] をクリックします。 これにより、アプリケーションはサインインしているユーザーの代わりに Azure Storage にアクセスできるようになります。
  • Azure Portal で RBAC を使用して Azure BLOB データへのアクセスを許可する

    • BLOB とキューの RBAC ロール - https://learn.microsoft.com/azure/storage/common/storage-auth-aad-rbac-portal
    • Azure portal で、ストレージ アカウントに移動し、ストレージ BLOB データ共同作成者 ロールを 、(azure-portal のストレージ アカウントの左側のナビゲーション バーにある) Access control (IAM) タブから登録済みの AAD アプリケーションに割り当てます。
  • サンプルの環境のセットアップ

    • AAD アプリケーションの概要ページで、CLIENT IDTENANT IDをメモします。 [証明書 & シークレット] タブでシークレットを作成し、下にメモします。
    • サンプルを正常に実行するための環境変数としてAZURE_TENANT_ID、AZURE_CLIENT_ID、AZURE_CLIENT_SECRETしていることを確認します (process.env を利用できます)。
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,
);

この方法を使用した完全な例については、Azure AD 認証のサンプル を参照してください。

[注 - 上記の手順は Node.js専用です]

接続文字列の使用

または、完全な接続文字列を引数として使用して、BlobServiceClient 静的メソッドを使用して fromConnectionString() をインスタンス化することもできます。 (接続文字列は Azure portal から取得できます)。[NODE.JS ランタイムでのみ使用可能]

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

const connStr = "<connection string>";

const blobServiceClient = BlobServiceClient.fromConnectionString(connStr);

StorageSharedKeyCredential

または、アカウント名とアカウント キーを引数として渡すことによって、BlobServiceClient を使用して StorageSharedKeyCredential をインスタンス化します。 (アカウント名とアカウント キーは、Azure portal から取得できます)。[NODE.JS ランタイムでのみ使用可能]

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,
);

SAS トークンを使用する

また、共有アクセス署名 (SAS) を使用して BlobServiceClient をインスタンス化することもできます。 Azure Portal から SAS トークンを取得することも、generateAccountSASQueryParameters()を使用して SAS トークンを生成することもできます。

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

新しいコンテナーを作成する

BlobServiceClient.getContainerClient() を使用してコンテナー クライアント インスタンスを取得し、新しいコンテナー リソースを作成します。

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);

コンテナーを一覧表示する

BlobServiceClient.listContainers() 関数を使用して、新しい 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 containers = blobServiceClient.listContainers();
for await (const container of containers) {
  console.log(`Container ${i++}: ${container.name}`);
}

または、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());
}

さらに、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.

データをアップロードして BLOB を作成する

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

コンテナー内の BLOB を一覧表示する

コンテナーの一覧表示に似ています。

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.

BLOB をダウンロードして文字列に変換する (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();
}

BLOB をダウンロードして文字列に変換します (ブラウザー)。

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

ログ記録を有効にすると、エラーに関する有用な情報を明らかにするのに役立つ場合があります。 HTTP 要求と応答のログを表示するには、AZURE_LOG_LEVEL 環境変数を infoに設定します。 または、setLogLevel@azure/logger を呼び出すことによって、実行時にログを有効にすることもできます。

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

Next steps

その他のコード サンプル:

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.

また、ストレージ ライブラリのテスト環境の設定に関する追加情報については、Storage 固有のガイドの を参照してください。