共用方式為


適用於 JavaScript 的 Azure 儲存體檔案共用用戶端程式庫 - 12.29.1 版

Azure 檔案服務提供雲端中完全受控的檔案共用,可透過業界標準伺服器消息塊 (SMB) 通訊協定來存取。 Azure 檔案共用可以透過 Windows、Linux 和 macOS 的雲端或內部部署部署同時掛接。 此外,您可以使用 Azure 檔案同步在 Windows Server 上快取 Azure 檔案共用,以便快速存取使用數據的位置。

此專案提供 JavaScript 中的用戶端連結庫,可讓您輕鬆地取用 azure 檔案記憶體服務Microsoft。

使用此套件中的用戶端連結庫來:

  • 取得/設定檔案服務屬性
  • 建立/列出/刪除檔案共用
  • 建立/列出/刪除檔案目錄
  • 建立/讀取/列出/更新/刪除檔案

注意:此套件先前是以 名稱 @azure/storage-file發行。 它已重新命名為 @azure/storage-file-share,以更符合即將推出的 Azure 記憶體檔案數據湖新套件,並提供一組一致的 API 來處理 Azure 上的檔案。

主要連結:

入門指南

目前支持的環境

如需詳細資訊,請參閱我們的支援原則

Prerequisites

安裝套件

安裝適用於 JavaScript 的 Azure 檔案記憶體用戶端連結庫的慣用方式是使用 npm 套件管理員。 在終端機視窗中輸入下列內容:

npm install @azure/storage-file-share

驗證用戶端

Azure 記憶體支援數種方式進行驗證。 若要與 Azure 記憶體檔案共用服務互動,您必須建立記憶體用戶端的實例,例如 ShareServiceClientShareClientShareDirectoryClient。 請參閱建立 範例,以深入了解驗證。

Compatibility

此連結庫與 Node.js 和瀏覽器相容,並針對 LTS Node.js 版本(>=8.16.0) 和最新版的 Chrome、Firefox 和 Edge 進行驗證。

Web Workers

此連結庫需要某些 DOM 對象在瀏覽器中使用時全域可用,Web 背景工作角色預設不會提供這些物件。 您必須進行聚合填入,才能讓此連結庫在 Web 背景工作。

如需詳細資訊,請參閱我們的 檔,以在 Web 背景工作角色中使用適用於 JS 的 Azure SDK

此連結庫取決於下列 DOM API,這些 API 需要在 Web 背景工作角色中使用時載入外部 polyfill:

Node.js 與瀏覽器之間的差異

Node.js 和瀏覽器運行時間之間有差異。 開始使用此連結庫時,請注意標示為「僅適用於NODE.JS運行時間」API 或類別,「只能在瀏覽器中使用」

  • 如果檔案以 gzipdeflate 格式保存壓縮的數據,且其內容編碼會據以設定,則下載行為在 Node.js 和瀏覽器之間會有所不同。 在 Node.js 記憶體用戶端會下載其壓縮格式的檔案,而在瀏覽器中,數據會以解壓縮格式下載。
下列功能、介面、類別或函式僅適用於 Node.js
  • 根據帳戶名稱和帳戶金鑰的共用金鑰授權
    • StorageSharedKeyCredential
  • 共用存取簽章(SAS) 產生
    • generateAccountSASQueryParameters()
    • generateFileSASQueryParameters()
  • 平行上傳和下載。 請注意,Node.js 和瀏覽器都提供 ShareFileClient.uploadData()
    • ShareFileClient.uploadFile()
    • ShareFileClient.uploadStream()
    • ShareFileClient.downloadToBuffer()
    • ShareFileClient.downloadToFile()
下列功能、介面、類別或函式僅適用於瀏覽器

N/A

JavaScript 套件組合

若要在瀏覽器中使用此用戶端連結庫,您必須先使用配套程式。 有關如何執行此操作的詳細信息,請參閱我們的 捆綁文件

CORS

如果您需要為瀏覽器進行開發,您必須為記憶體帳戶設定 跨原始資源分享 (CORS) 規則。 移至 Azure 入口網站和 Azure 記憶體總管,尋找您的記憶體帳戶,為 Blob/佇列/檔案/資料表服務建立新的 CORS 規則。

例如,您可以建立下列 CORS 設定以進行偵錯。 但請根據您的生產環境中的需求,仔細自定義設定。

  • 允許的來源: *
  • 允許的動詞:DELETE、GET、HEAD、MERGE、POST、OPTIONS、PUT
  • 允許的標頭: *
  • 公開的標頭: *
  • 年齡上限(秒):86400

重要概念

下列元件及其對應的用戶端連結庫組成 Azure 記憶體檔案共享服務:

  • 儲存體帳戶本身,以ShareServiceClient
  • 儲存體帳戶內的 檔案共用 ,以 ShareClient
  • 檔案共享內目錄 的選擇性 階層,以 實例表示
  • 檔案共用內的 檔案 ,其大小可能高達 1 TiB,以 ShareFileClient

Examples

匯入套件

若要使用用戶端,請將套件匯入您的檔案:

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

或者,選擇性地只匯入您需要的類型:

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

建立共用服務用戶端

ShareServiceClient 需要檔案共享服務的 URL 和存取認證。 它也會選擇性地接受 options 參數中的一些設定。

使用連接字串

或者,您可以使用具有完整連接字串做為自變數的 ShareServiceClient 靜態方法,具現化 fromConnectionString()。 (您可以從 Azure 入口網站取得連接字串。

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

const connectionString = "<connection string>";

const shareServiceClient = ShareServiceClient.fromConnectionString(connectionString);

搭配 StorageSharedKeyCredential

使用您的帳戶名稱和帳戶金鑰傳入 StorageSharedKeyCredential。 (帳戶名稱和帳戶密鑰可以從 Azure 入口網站取得。

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令牌

此外,您可以使用共用存取簽章來具現化 ShareServiceClient(SAS)。 您可以從 Azure 入口網站取得 SAS 令牌,或使用 generateAccountSASQueryParameters()產生。

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 屬性可用來識別反覆運算是目錄還是檔案。

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

如果您想要參與此連結庫,請閱讀 參與指南 ,以深入瞭解如何建置和測試程序代碼。

另請參閱 儲存體特定指南,以取得設定記憶體連結庫測試環境的其他資訊。