次の方法で共有


JavaScript 用の Azure Storage ファイル共有クライアント ライブラリ - バージョン 12.28.0

Azure Files には、業界標準のサーバー メッセージ ブロック (SMB) プロトコルを介してアクセスできるフル マネージドのファイル共有がクラウドに用意されています。 Azure ファイル共有は、Windows、Linux、macOS のクラウドまたはオンプレミスのデプロイによって同時にマウントできます。 さらに、Azure ファイル共有は、データが使用されている場所の近くで高速にアクセスできるように、Azure File Sync を使用して Windows Server にキャッシュできます。

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

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

  • ファイル サービスのプロパティの取得/設定
  • ファイル共有の作成/一覧表示/削除
  • ファイル ディレクトリの作成/一覧表示/削除
  • Create/Read/List/Update/Delete Files

注: このパッケージは、以前に @azure/storage-fileという名前で公開されました。 Azure Storage Files DataLake の今後の新しいパッケージに合わせ、Azure 上のファイルを操作するための一貫した API セットを提供するために、@azure/storage-file-share に名前が変更されました。

Key links:

Getting started

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

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

See our support policy for more details.

Prerequisites

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

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

npm install @azure/storage-file-share

クライアントを認証する

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

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 またはクラスに注意してください。

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

N/A

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

次のコンポーネントとそれに対応するクライアント ライブラリは、Azure Storage ファイル共有サービスを構成します。

  • The storage account itself, represented by a ShareServiceClient
  • A file share within the storage account, represented by a ShareClient
  • インスタンスによって表される、ファイル共有内で ディレクトリの省略可能な 階層
  • A file within the file share, which may be up to 1 TiB in size, represented by a ShareFileClient

Examples

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

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

import * as AzureStorageFileShare from "@azure/storage-file-share";

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

import { ShareServiceClient, StorageSharedKeyCredential } from "@azure/storage-file-share";

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

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

接続文字列の使用

または、完全な接続文字列を引数として使用して、ShareServiceClient 静的メソッドを使用して fromConnectionString() をインスタンス化することもできます。 (接続文字列は Azure portal から取得できます)。

import { ShareServiceClient } from "@azure/storage-file-share";

const connectionString = "<connection string>";

const shareServiceClient = ShareServiceClient.fromConnectionString(connectionString);

StorageSharedKeyCredential

アカウント名とアカウント キーを使用して StorageSharedKeyCredential を渡します。 (アカウント名とアカウント キーは、Azure portal から取得できます)。

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

// Enter your storage account name and shared key
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 credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  // When using AnonymousCredential, following url should include a valid SAS
  `https://${account}.file.core.windows.net`,
  credential,
);

SAS トークンを使用する

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

import { ShareServiceClient } from "@azure/storage-file-share";

const account = "<account name>";
const sas = "<service Shared Access Signature Token>";

const serviceClientWithSAS = new ShareServiceClient(
  `https://${account}.file.core.windows.net?${sas}`,
);

アカウント内の共有を一覧表示する

ShareServiceClient.listShares() を使用して、新しい for-await-of 構文を使用して、このアカウント内の共有を反復子します。

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

let i = 1;
for await (const share of serviceClient.listShares()) {
  console.log(`Share${i++}: ${share.name}`);
}

または、for-await-ofを使用しない場合:

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareIter = serviceClient.listShares();
let i = 1;
let { value, done } = await shareIter.next();
while (!done) {
  console.log(`Share ${i++}: ${value.name}`);
  ({ value, done } = await shareIter.next());
}

新しい共有とディレクトリを作成する

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = `newshare${+new Date()}`;
const shareClient = serviceClient.getShareClient(shareName);
await shareClient.create();
console.log(`Create share ${shareName} successfully`);

const directoryName = `newdirectory${+new Date()}`;
const directoryClient = shareClient.getDirectoryClient(directoryName);
await directoryClient.create();
console.log(`Create directory ${directoryName} successfully`);

Azure ファイルを作成してアップロードする

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

const content = "Hello World!";
const fileName = `newdirectory${+new Date()}`;
const fileClient = directoryClient.getFileClient(fileName);
await fileClient.create(content.length);
console.log(`Create file ${fileName} successfully`);

// Upload file range
await fileClient.uploadRange(content, 0, content.length);
console.log(`Upload file range "${content}" to ${fileName} successfully`);

ディレクトリの下にあるファイルとディレクトリを一覧表示する

DirectoryClient.listFilesAndDirectories() を使用して、新しい for-await-of 構文を使用してファイルとディレクトリを反復子します。 kind プロパティを使用して、iterm がディレクトリかファイルかを識別できます。

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

let i = 1;
for await (const item of directoryClient.listFilesAndDirectories()) {
  if (item.kind === "directory") {
    console.log(`${i} - directory\t: ${item.name}`);
  } else {
    console.log(`${i} - file\t: ${item.name}`);
  }
  i++;
}

または、for-await-ofを使用せずに:

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

let i = 1;
const iter = directoryClient.listFilesAndDirectories();
let { value, done } = await iter.next();
while (!done) {
  if (value.kind === "directory") {
    console.log(`${i} - directory\t: ${value.name}`);
  } else {
    console.log(`${i} - file\t: ${value.name}`);
  }
  ({ value, done } = await iter.next());
  i++;
}

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

ファイルをダウンロードして文字列に変換する (Node.js)

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const fileName = "<file name>";
const fileClient = serviceClient
  .getShareClient(shareName)
  .rootDirectoryClient.getFileClient(fileName);

// Get file content from position 0 to the end
// In Node.js, get downloaded data by accessing downloadFileResponse.readableStreamBody
const downloadFileResponse = await fileClient.download();
if (downloadFileResponse.readableStreamBody) {
  const buffer = await streamToBuffer(downloadFileResponse.readableStreamBody);
  console.log(`Downloaded file content: ${buffer.toString()}`);
}

// [Node.js only] A helper method used to read a Node.js readable stream into a Buffer
async function streamToBuffer(readableStream: NodeJS.ReadableStream): Promise<Buffer> {
  return new Promise((resolve, reject) => {
    const chunks: Buffer[] = [];
    readableStream.on("data", (data) => {
      chunks.push(data instanceof Buffer ? data : Buffer.from(data));
    });
    readableStream.on("end", () => {
      resolve(Buffer.concat(chunks));
    });
    readableStream.on("error", reject);
  });
}

ファイルをダウンロードして文字列に変換する (ブラウザー)

Please refer to the JavaScript Bundle section for more information on using this library in the browser.

import { ShareServiceClient } from "@azure/storage-file-share";

const account = "<account name>";
const sas = "<service Shared Access Signature Token>";

const serviceClient = new ShareServiceClient(`https://${account}.file.core.windows.net?${sas}`);

const shareName = "<share name>";
const fileName = "<file name>";
const fileClient = serviceClient
  .getShareClient(shareName)
  .rootDirectoryClient.getFileClient(fileName);

// Get file content from position 0 to the end
// In browsers, get downloaded data by accessing downloadFileResponse.blobBody
const downloadFileResponse = await fileClient.download(0);
if (downloadFileResponse.blobBody) {
  console.log(`Downloaded file content: ${(await downloadFileResponse.blobBody).text()}`);
}

A complete example of simple ShareServiceClient scenarios is at samples/v12/typescript/src/shareSerivceClient.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 固有のガイドの を参照してください。