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 リファレンス ドキュメント
- 製品のドキュメント
- サンプル
- Azure Storage File REST API を
する
はじめ
現在サポートされている環境
- Node.js の LTS バージョンを
する - Safari、Chrome、Edge、Firefox の最新バージョン。
詳細については、サポート ポリシーの を参照してください。
前提 条件
パッケージをインストールする
JavaScript 用の Azure File Storage クライアント ライブラリをインストールする場合は、npm パッケージ マネージャーを使用することをお勧めします。 ターミナル ウィンドウに次のように入力します。
npm install @azure/storage-file-share
クライアントを認証する
Azure Storage では、いくつかの認証方法がサポートされています。 Azure Storage ファイル共有サービスと対話するには、ストレージ クライアントのインスタンス (ShareServiceClient
、ShareClient
、ShareDirectoryClient
など) を作成する必要があります。 認証の詳細については、
- 共有キー の
- Shared Access Signature
互換性
このライブラリは、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 とブラウザーのランタイムには違いがあります。 このライブラリの使用を開始するときは、
- ファイルが圧縮データを
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
で表されます。
例
- パッケージ をインポート
- 共有サービス クライアント を作成する
- アカウント の共有を一覧表示する
- 新しい共有とディレクトリ を作成する
- Azure ファイルを作成し、 にアップロードします
- ディレクトリ の下にあるファイルとディレクトリを一覧表示する
- ファイルをダウンロードし、文字列 (Node.js) に変換
- ファイルをダウンロードして文字列に変換する (ブラウザー)
パッケージをインポートする
クライアントを使用するには、パッケージをファイルにインポートします。
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 トークンを使用する
また、共有アクセス署名 (SAS) を使用して ShareServiceClient
をインスタンス化することもできます。 Azure Portal から SAS トークンを取得することも、generateAccountSASQueryParameters()
を使用して SAS トークンを生成することもできます。
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}`
);
アカウント内の共有を一覧表示する
ShareServiceClient.listShares()
を使用して、新しい 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() {
const 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() {
const 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();
ディレクトリの下にあるファイルとディレクトリを一覧表示する
DirectoryClient.listFilesAndDirectories()
を使用して、新しい for-await-of
構文を使用してファイルとディレクトリを反復子します。
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);
const 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);
const 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}`);
}
i++;
item = await dirIter.next();
}
}
main();
反復処理の完全なサンプルについては、サンプル/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_LEVEL
環境変数を info
に設定します。 または、setLogLevel
で @azure/logger
を呼び出すことによって、実行時にログを有効にすることもできます。
const { setLogLevel } = require("@azure/logger");
setLogLevel("info");
次の手順
その他のコード サンプル
貢献
このライブラリに投稿する場合は、コードをビルドしてテストする方法の詳細については、投稿ガイド を参照してください。
また、ストレージ ライブラリのテスト環境の設定に関する追加情報については、Storage 固有のガイドの を参照してください。
Azure SDK for JavaScript