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

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

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

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

  • ファイル サービスのプロパティを取得/設定する
  • ファイル共有の作成/一覧表示/削除
  • ファイル ディレクトリの作成/一覧表示/削除
  • ファイルの作成/読み取り/一覧表示/更新/削除

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

主要リンク:

はじめに

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

詳細については、Microsoft のサポート ポリシーを参照してください。

前提条件

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

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

npm install @azure/storage-file-share

クライアントを認証する

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

互換性

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

Web Worker

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

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

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

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

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

  • ファイルが圧縮されたデータを または deflate 形式でgzip保持し、そのコンテンツ エンコードがそれに応じて設定されている場合、ダウンロード動作は 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()
以下の機能、インターフェイス、クラス、または関数はブラウザーでのみ使用できます

該当なし

JavaScript バンドル

ブラウザーでこのクライアント ライブラリを使用するには、まず bundler を使用する必要があります。 これを行う方法の詳細については、 バンドルに関するドキュメントを参照してください。

CORS

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

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

  • 許可される配信元: *
  • 使用できる動詞: DELETE、GET、HEAD、MERGE、POST、OPTIONS、PUT
  • 許可されるヘッダー: *
  • 公開されているヘッダー: *
  • 最大経過時間 (秒): 86400

主要な概念

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

  • によって表される ストレージ アカウント 自体 ShareServiceClient
  • によって表されるストレージ アカウント内のファイル共有ShareClient
  • インスタンスでShareDirectoryClient表されるファイル共有内のディレクトリのオプションの階層
  • ファイル共有内の ファイル (最大 1 TiB のサイズで、 で表される場合があります) ShareFileClient

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

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

const AzureStorageFileShare = require("@azure/storage-file-share");

別の方法として、必要な型のみを選択的にインポートします。

const { ShareServiceClient, StorageSharedKeyCredential } = require("@azure/storage-file-share");

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

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

接続文字列の使用

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

const { ShareServiceClient } = require("@azure/storage-file-share");

const connStr = "<connection string>";

const shareServiceClient = ShareServiceClient.fromConnectionString(connStr);

を使用する StorageSharedKeyCredential

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

const { ShareServiceClient, StorageSharedKeyCredential } = require("@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 トークンを使用する

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

const { ShareServiceClient } = require("@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}`
);

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

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

const { ShareServiceClient, StorageSharedKeyCredential } = require("@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
);

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

main();

または、 を使用しません for-await-of

const { ShareServiceClient, StorageSharedKeyCredential } = require("@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
);

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

main();

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

const { ShareServiceClient, StorageSharedKeyCredential } = require("@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
);

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

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

main();

Azure ファイルを作成し、それにアップロードする

const { ShareServiceClient, StorageSharedKeyCredential } = require("@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>";

async function main() {
  const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

  const content = "Hello World!";
  const fileName = "newfile" + new Date().getTime();
  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`);
}

main();

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

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

const { ShareServiceClient, StorageSharedKeyCredential } = require("@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>";

async function main() {
  const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

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

main();

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

const { ShareServiceClient, StorageSharedKeyCredential } = require("@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>";

async function main() {
  const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

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

main();

反復処理の完全なサンプルについては、 samples/v12/typescript/src/listFilesAndDirectories.ts を参照してください。

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

const { ShareServiceClient, StorageSharedKeyCredential } = require("@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>";

// [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(data instanceof Buffer ? data : Buffer.from(data));
    });
    readableStream.on("end", () => {
      resolve(Buffer.concat(chunks));
    });
    readableStream.on("error", reject);
  });
}

async function main() {
  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();
  console.log(
    `Downloaded file content: ${(
      await streamToBuffer(downloadFileResponse.readableStreamBody)
    ).toString()}`
  );
}

main();

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

ブラウザーでのこのライブラリの使用の詳細については、 JavaScript バンドル に関するセクションを参照してください。

const { ShareServiceClient } = require("@azure/storage-file-share");

const account = "<account name>";
const sas = "<service Shared Access Signature Token>";
const shareName = "<share name>";
const fileName = "<file name>";

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

async function main() {
  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);
  console.log(
    `Downloaded file content: ${await blobToString(await downloadFileResponse.blobBody)}`
  );
}

// [Browser 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();

単純なシナリオの完全な ShareServiceClient 例は 、samples/v12/typescript/src/shareSerivceClient.ts にあります

トラブルシューティング

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

const { setLogLevel } = require("@azure/logger");

setLogLevel("info");

次のステップ

その他のコード サンプル

共同作成

このライブラリに投稿する場合、コードをビルドしてテストする方法の詳細については、投稿ガイドを参照してください。

ストレージ ライブラリのテスト環境を設定する方法の詳細については、「ストレージ 固有のガイド 」も参照してください。

インプレッション数