@azure/storage-file-share

中文文档
12.33.0发布于 2026/09/25MITTypeScriptESM + CJS近 30 天下载 93.6万

Microsoft Azure Storage SDK for JavaScript - File

原始使用文档
文档目录22 节
  1. Getting started
  2. Currently supported environments
  3. Prerequisites
  4. Install the package
  5. Authenticate the client
  6. Compatibility
  7. JavaScript Bundle
  8. CORS
  9. Key concepts
  10. Examples
  11. Import the package
  12. Create the share service client
  13. List shares in the account
  14. Create a new share and a directory
  15. Create an azure file then upload to it
  16. List ranges of a file
  17. List files and directories under a directory
  18. Download a file and convert it to a string (Node.js)
  19. Download a file and convert it to a string (Browsers)
  20. Troubleshooting
  21. Next steps
  22. Contributing

Azure Storage File Share client library for JavaScript

Azure Files offers fully managed file shares in the cloud that are accessible via the industry standard Server Message Block (SMB) protocol. Azure file shares can be mounted concurrently by cloud or on-premises deployments of Windows, Linux, and macOS. Additionally, Azure file shares can be cached on Windows Servers with Azure File Sync for fast access near where the data is being used.

This project provides a client library in JavaScript that makes it easy to consume Microsoft Azure File Storage service.

Use the client libraries in this package to:

  • Get/Set File Service Properties
  • Create/List/Delete File Shares
  • Create/List/Delete File Directories
  • Create/Read/List/Update/Delete Files

Note: This package was previously published under the name @azure/storage-file. It has been renamed to @azure/storage-file-share to better align with the upcoming new package for Azure Storage Files DataLake and provide a consistent set of APIs for working with files on Azure.

Key links:

Getting started

Currently supported environments

See our support policy for more details.

Prerequisites

Install the package

The preferred way to install the Azure File Storage client library for JavaScript is to use the npm package manager. Type the following into a terminal window:

npm install @azure/storage-file-share

Authenticate the client

Azure Storage supports several ways to authenticate. In order to interact with the Azure Storage File Share service you'll need to create an instance of a Storage client - ShareServiceClient, ShareClient, or ShareDirectoryClient for example. See samples for creating the ShareServiceClient to learn more about authentication.

Compatibility

This library is compatible with Node.js and browsers, and validated against LTS Node.js versions (>=8.16.0) and latest versions of Chrome, Firefox and Edge.

Web Workers

This library requires certain DOM objects to be globally available when used in the browser, which web workers do not make available by default. You will need to polyfill these to make this library work in web workers.

For more information please refer to our documentation for using Azure SDK for JS in Web Workers

This library depends on following DOM APIs which need external polyfills loaded when used in web workers:

Differences between Node.js and browsers

There are differences between Node.js and browsers runtime. When getting started with this library, pay attention to APIs or classes marked with "ONLY AVAILABLE IN NODE.JS RUNTIME" or "ONLY AVAILABLE IN BROWSERS".

  • If a file holds compressed data in gzip or deflate format and its content encoding is set accordingly, downloading behavior is different between Node.js and browsers. In Node.js storage clients will download the file in its compressed format, while in browsers the data will be downloaded in de-compressed format.
Following features, interfaces, classes or functions are only available in Node.js
  • Shared Key Authorization based on account name and account key
    • StorageSharedKeyCredential
  • Shared Access Signature(SAS) generation
    • generateAccountSASQueryParameters()
    • generateFileSASQueryParameters()
  • Parallel uploading and downloading. Note that ShareFileClient.uploadData() is available in both Node.js and browsers.
    • ShareFileClient.uploadFile()
    • ShareFileClient.uploadStream()
    • ShareFileClient.downloadToBuffer()
    • ShareFileClient.downloadToFile()
Following features, interfaces, classes or functions are only available in browsers

N/A

JavaScript Bundle

To use this client library in the browser, first you need to use a bundler. For details on how to do this, please refer to our bundling documentation.

CORS

You need to set up Cross-Origin Resource Sharing (CORS) rules for your storage account if you need to develop for browsers. Go to Azure portal and Azure Storage Explorer, find your storage account, create new CORS rules for blob/queue/file/table service(s).

For example, you can create following CORS settings for debugging. But please customize the settings carefully according to your requirements in production environment.

  • Allowed origins: *
  • Allowed verbs: DELETE,GET,HEAD,MERGE,POST,OPTIONS,PUT
  • Allowed headers: *
  • Exposed headers: *
  • Maximum age (seconds): 86400

Key concepts

The following components and their corresponding client libraries make up the Azure Storage File Share service:

  • The storage account itself, represented by a ShareServiceClient
  • A file share within the storage account, represented by a ShareClient
  • An optional hierarchy of directories within the file share, represented by ShareDirectoryClient instances
  • A file within the file share, which may be up to 1 TiB in size, represented by a ShareFileClient

Examples

Import the package

To use the clients, import the package into your file:

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

Alternative, selectively import only the types you need:

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

Create the share service client

The ShareServiceClient requires an URL to the file share service and an access credential. It also optionally accepts some settings in the options parameter.

using connection string

Alternatively, you can instantiate a ShareServiceClient using the fromConnectionString() static method with the full connection string as the argument. (The connection string can be obtained from the azure portal.)

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

const connectionString = "<connection string>";

const shareServiceClient = ShareServiceClient.fromConnectionString(connectionString);

with StorageSharedKeyCredential

Pass in a StorageSharedKeyCredential with your account name and account key. (The account-name and account-key can be obtained from the 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,
);

with SAS Token

Also, You can instantiate a ShareServiceClient with a shared access signatures (SAS). You can get the SAS token from the Azure Portal or generate one using 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}`,
);

List shares in the account

Use ShareServiceClient.listShares() to iterator shares in this account, with the new for-await-of syntax:

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}`);
}

Alternatively without 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());
}

Create a new share and a directory

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`);

Create an azure file then upload to it

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`);

List ranges of a file

Use ShareFileClient.listRanges() to enumerate the valid byte ranges of a file as a paginated async iterable. Each item is a ShareFileRange with start, end, and isClear. Use ShareFileClient.listRangesDiff() to list the ranges that changed since a previous share snapshot; cleared ranges are returned with isClear set to true.

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

// Each item is a ShareFileRange with start, end, and isClear
for await (const range of fileClient.listRanges()) {
  console.log(`Range: ${range.start}-${range.end}, isClear: ${range.isClear}`);
}

Use .byPage() to control the page size and resume from a continuation token:

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 the first page of ranges
let iterator = fileClient.listRanges().byPage({ maxPageSize: 1 });
let response = (await iterator.next()).value;
for (const range of response.ranges || []) {
  console.log(`Range: ${range.start}-${range.end}`);
}

// Gets next marker
const marker = response.continuationToken;

// Passing next marker as continuationToken
iterator = fileClient.listRanges().byPage({ continuationToken: marker, maxPageSize: 2 });
response = (await iterator.next()).value;
for (const range of response.ranges || []) {
  console.log(`Range: ${range.start}-${range.end}`);
}

List files and directories under a directory

Use DirectoryClient.listFilesAndDirectories() to iterator over files and directories, with the new for-await-of syntax. The kind property can be used to identify whether a iterm is a directory or a file.

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++;
}

Alternatively without using 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++;
}

For a complete sample on iterating please see samples/v12/typescript/src/listFilesAndDirectories.ts.

Download a file and convert it to a string (Node.js)

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";
import { buffer } from "node:stream/consumers";

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) {
  // Download the raw bytes of the file. Use `text` from "node:stream/consumers"
  // instead if you want to read the content as a string directly.
  const downloaded = await buffer(downloadFileResponse.readableStreamBody);
  console.log(`Downloaded file content: ${downloaded.toString()}`);
}

Download a file and convert it to a string (Browsers)

Please refer to the JavaScript Bundle section for more information on using this library in the browser.

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()}`);
}

A complete example of simple ShareServiceClient scenarios is at samples/v12/typescript/src/shareSerivceClient.ts.

Troubleshooting

Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the AZURE_LOG_LEVEL environment variable to info. Alternatively, logging can be enabled at runtime by calling setLogLevel in the @azure/logger:

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

setLogLevel("info");

Next steps

More code samples

Contributing

If you'd like to contribute to this library, please read the contributing guide to learn more about how to build and test the code.

Also refer to Storage specific guide for additional information on setting up the test environment for storage libraries.

版本与发布记录

@azure/storage-file-share 共发布 530 个版本,首次发布于 2019/10/31;过去 12 个月发布了 47 个版本。

版本发布日期距今
12.33.0latest2026/09/251 个月前
12.33.0-beta.1beta2026/08/043 个月前
12.32.02026/06/244 个月前
12.31.02026/06/055 个月前
12.32.0-beta.12026/05/095 个月前
12.31.0-alpha.20260310.1dev2026/03/117 个月前

其他发布通道:next → 12.29.0-beta.1,dev → 12.31.0-alpha.20260310.1,beta → 12.33.0-beta.1。

关于 @azure/storage-file-share 的常见问题

@azure/storage-file-share 是什么?

Microsoft Azure Storage SDK for JavaScript - File

如何安装 @azure/storage-file-share?

在项目目录运行 npm install @azure/storage-file-share,或使用 pnpm add / yarn add / bun add。

@azure/storage-file-share 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@azure/storage-file-share 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@azure/storage-file-share 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@azure/storage-file-share 可以商用吗?

@azure/storage-file-share 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@azure/storage-file-share 的下载量有多少?

根据 npm 官方下载统计,@azure/storage-file-share 在 2026/10/08 – 2026/11/06 这 30 天内被下载 935,563 次,日均约 31,185 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@azure/storage-file-share 还在维护吗?

最新版本 12.33.0 发布于 2026/09/25(1 个月前);至今共发布 530 个版本,其中过去 12 个月发布了 47 个;首次发布于 2019/10/31。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。