Azure Files には、業界標準のサーバー メッセージ ブロック (SMB) プロトコルを介してアクセスできるフル マネージドのファイル共有がクラウドに用意されています。 Azure ファイル共有は、Windows、Linux、macOS のクラウドまたはオンプレミスのデプロイによって同時にマウントできます。 さらに、Azure ファイル共有は、データが使用されている場所の近くで高速にアクセスできるように、Azure File Sync を使用して Windows Server にキャッシュできます。
このプロジェクトは、Microsoft Azure File Storage サービスを簡単に使用できる JavaScript のクライアント ライブラリを提供します。
このパッケージのクライアント ライブラリを使用して、次の操作を行います。
- ファイル サービスのプロパティの取得/設定
- ファイル共有の作成/一覧表示/削除
- ファイル ディレクトリの作成/一覧表示/削除
- ファイルの作成/読み取り/一覧表示/更新/削除
注: このパッケージは、以前に
@azure/storage-fileという名前で公開されました。 Azure Storage Files DataLake の今後の新しいパッケージに合わせ、Azure 上のファイルを操作するための一貫した API セットを提供するために、@azure/storage-file-shareに名前が変更されました。
主要なリンク:
- ソースコード
- パッケージ (npm)
- API リファレンス ドキュメント
- 製品ドキュメント
- Samples
- Azure Storage File REST API を
する
作業の開始
現在サポートされている環境
- Node.js の LTS バージョンを
する - Safari、Chrome、Edge、Firefox の最新バージョン。
詳細については、 サポート ポリシー を参照してください。
Prerequisites
パッケージをインストールする
JavaScript 用の Azure File Storage クライアント ライブラリをインストールする場合は、npm パッケージ マネージャーを使用することをお勧めします。 ターミナル ウィンドウに次のように入力します。
npm install @azure/storage-file-share
クライアントを認証する
Azure Storage では、いくつかの認証方法がサポートされています。 Azure Storage ファイル共有サービスと対話するには、ストレージ クライアントのインスタンス (ShareServiceClient、ShareClient、ShareDirectoryClient など) を作成する必要があります。 認証の詳細については、
Compatibility
このライブラリは、Node.js とブラウザーと互換性があり、LTS Node.js バージョン (>=8.16.0) と Chrome、Firefox、Edge の最新バージョンに対して検証されます。
Web ワーカー
このライブラリでは、ブラウザーで使用する場合、特定の DOM オブジェクトをグローバルに使用できる必要があります。Web ワーカーは既定では使用できません。 Web ワーカーでこのライブラリを動作させるには、これらをポリフィルする必要があります。
詳細については、Web Worker で Azure SDK for JS を使用するための ドキュメントを参照してください
このライブラリは、Web ワーカーで使用するときに外部ポリフィルを読み込む必要がある次の DOM API に依存します。
Node.js とブラウザーの違い
Node.js とブラウザーのランタイムには違いがあります。 このライブラリの使用を開始するときは、
- ファイルが圧縮データを
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 バンドル
ブラウザーでこのクライアント ライブラリを使用するには、まず、バンドルを使用する必要があります。 これを行う方法の詳細については、
CORS
ブラウザー用に開発する必要がある場合は、ストレージ アカウント クロスオリジン リソース共有 (CORS) 規則を設定する必要があります。 Azure portal と Azure Storage Explorer に移動し、ストレージ アカウントを見つけ、BLOB/キュー/ファイル/テーブル サービス用の新しい CORS ルールを作成します。
たとえば、デバッグ用に次の CORS 設定を作成できます。 ただし、運用環境の要件に合わせて設定を慎重にカスタマイズしてください。
- 許可される配信元: *
- 使用できる動詞: DELETE、GET、HEAD、MERGE、POST、OPTIONS、PUT
- 許可されるヘッダー: *
- 公開されたヘッダー: *
- 最長有効期間 (秒): 86400
重要な概念
次のコンポーネントとそれに対応するクライアント ライブラリは、Azure Storage ファイル共有サービスを構成します。
-
ストレージ アカウント自体は、
ShareServiceClient - ストレージ アカウント内の ファイル共有 (
ShareClient インスタンスによって表される、ファイル共有内で ディレクトリの省略可能な 階層 - ファイル共有内の ファイル (最大 1 TiB のサイズ) で表されます。
ShareFileClient
Examples
- パッケージ をインポート
- 共有サービス クライアント を作成する
- アカウント の共有を一覧表示する
- 新しい共有とディレクトリ を作成する
- Azure ファイルを作成し、 にアップロードします
- ディレクトリ の下にあるファイルとディレクトリを一覧表示する
- ファイルをダウンロードし、文字列 (Node.js) に変換
- ファイルをダウンロードして文字列に変換する (ブラウザー)
パッケージをインポートする
クライアントを使用するには、パッケージをファイルにインポートします。
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++;
}
反復に関する完全なサンプルについては、 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);
});
}
ファイルをダウンロードして文字列に変換する (ブラウザー)
ブラウザーでこのライブラリを使用する方法の詳細については、「 JavaScript バンドル 」セクションを参照してください。
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()}`);
}
単純な ShareServiceClient シナリオの完全な例は、 samples/v12/typescript/src/shareSerivceClient.tsにあります。
Troubleshooting
ログ記録を有効にすると、エラーに関する有用な情報を明らかにするのに役立つ場合があります。 HTTP 要求と応答のログを表示するには、AZURE_LOG_LEVEL 環境変数を infoに設定します。 または、setLogLevelで @azure/logger を呼び出すことによって、実行時にログを有効にすることもできます。
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
次のステップ
その他のコード サンプル
Contributing
このライブラリに投稿する場合は、コードをビルドしてテストする方法の詳細については、 投稿ガイド をお読みください。
また、ストレージ ライブラリのテスト環境の設定に関する追加情報については、Storage 固有のガイドの を参照してください。
Azure SDK for JavaScript