次の方法で共有


JavaScript Readme のAzure Files - バージョン 12.1.1

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 上のファイルを操作するための一貫した API セットを提供するために、 に名前が変更 @azure/storage-file-share されました。

ソースコード | パッケージ (npm) | API リファレンス ドキュメント | 製品ドキュメント | サンプル | Azure Storage File REST API

作業の開始

前提条件: このパッケージを使用するには、 Azure サブスクリプションストレージ アカウント が必要です。 Node.js アプリケーションでこのパッケージを使用している場合は、バージョン 8.0.0 以降Node.js必要です。

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

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

npm install @azure/storage-file-share

クライアントを認証する

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

互換性

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

IE11 と互換性がある

IE11 でこのライブラリを動作させるには、ポリフィルが必要です。 最も簡単な方法は、 @babel/ポリフィル、または ポリフィル サービスを使用することです。

また、見逃した ES 機能に対して個別のポリフィルを読み込むこともできます。 このライブラリは、外部ポリフィルを読み込む必要がある次の ES 機能に依存します。

  • Promise
  • String.prototype.startsWith
  • String.prototype.endsWith
  • String.prototype.repeat
  • String.prototype.includes
  • Array.prototype.includes
  • Object.assign
  • Object.keys (ES6 動作を有効にするには、IE11 の Object.keysES6 ポリフィルで強制的にオーバーライドします)
  • Symbol
  • Symbol.iterator

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

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

次の機能、インターフェイス、クラス、または関数は、Node.jsでのみ使用できます
  • アカウント名とアカウント キーに基づく共有キーの承認
    • StorageSharedKeyCredential
  • Shared Access Signature(SAS) の生成
    • generateAccountSASQueryParameters()
    • generateFileSASQueryParameters()
  • 並列アップロードとダウンロード
    • ShareFileClient.uploadFile()
    • ShareFileClient.uploadStream()
    • ShareFileClient.downloadToBuffer()
    • ShareFileClient.downloadToFile()
次の機能、インターフェイス、クラス、または関数はブラウザーでのみ使用できます
  • 並列アップロードとダウンロード
    • ShareFileClient.uploadBrowserData()

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 受け入れます。

with 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 avaiable 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 = await 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 = await 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/iterators-files-and-directories.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 string
async function streamToString(readableStream) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    readableStream.on("data", (data) => {
      chunks.push(data.toString());
    });
    readableStream.on("end", () => {
      resolve(chunks.join(""));
    });
    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 streamToString(downloadFileResponse.readableStreamBody)}`
  );
}

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

基本的なシナリオの完全な例は 、samples/basic.ts にあります

トラブルシューティング

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

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

setLogLevel("info");

次のステップ

その他のコード サンプル