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

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

此專案在 JavaScript 中提供用戶端程式庫,可讓您輕鬆地取用 Microsoft Azure 檔案儲存體服務。

使用此套件中的用戶端程式庫來:

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

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

重要連結:

開始使用

目前支援的環境

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

必要條件

安裝套件

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

npm install @azure/storage-file-share

驗證用戶端

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

相容性

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

Web 背景工作

此程式庫需要某些 DOM 物件在瀏覽器中使用時全域可用,而網頁背景工作角色預設不會提供這些物件。 您必須進行 polyfill,才能讓此程式庫在 Web 背景工作角色中運作。

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

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

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

Node.js 和瀏覽器執行時間之間有差異。 開始使用此程式庫時,請留意標示為 「僅適用于 NODE.JS 執行時間」「僅適用于瀏覽器」的API 或類別。

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

N/A

JavaScript 套件組合

若要在瀏覽器中使用此用戶端程式庫,您必須先使用套件組合器。 如需如何執行這項操作的詳細資訊,請參閱我們的 統合檔

CORS

如果您需要針對瀏覽器進行開發,您必須為儲存體帳戶設定 跨原始來源資源分享 (CORS) 規則。 移至 Azure 入口網站 和 Azure 儲存體總管,尋找您的儲存體帳戶,為 blob/queue/file/table 服務建立新的 CORS 規則, (s) 。

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

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

重要概念

下列元件及其對應的用戶端程式庫組成 Azure 儲存體檔案共用服務:

  • 儲存體帳戶本身,由 表示ShareServiceClient
  • 儲存體帳戶內的 檔案共用 ,由 表示 ShareClient
  • 檔案共用內 目錄的選擇性階層 ,由 ShareDirectoryClient 實例表示
  • 檔案共用內的 檔案 ,大小上限為 1 TiB,由 表示 ShareFileClient

範例

匯入封裝

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

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

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

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

建立共用服務用戶端

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

使用 連接字串

或者,您可以使用靜態方法具現化 ShareServiceClientfromConnectionString() ,並將完整連接字串作為引數。 (您可以從 azure portal.) 取得連接字串

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

const connStr = "<connection string>";

const shareServiceClient = ShareServiceClient.fromConnectionString(connStr);

with StorageSharedKeyCredential

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

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 入口網站取得 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}`
);

列出帳戶中的共用

使用 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() {
  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();

列出目錄下的檔案和目錄

使用 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);

  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_LEVEL 環境變數設定為 info。 或者,您可以在 @azure/logger 中呼叫 setLogLevel,以在執行階段啟用記錄:

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

setLogLevel("info");

後續步驟

更多程式碼範例

參與

如果您希望向此程式庫投稿,請參閱投稿指南,深入瞭解如何組建與測試程式碼。

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

曝光數