# @azure/storage-file-share 中文文档

规范地址：https://npmcn.com/package/%40azure/storage-file-share/

版本：12\.33\.0
npm 元数据更新时间：2026-09-24T18:23:19.606Z
中文译文更新时间：2026-11-07T13:18:44.982Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40azure/storage-file-share
原文对照：https://npmcn.com/package/%40azure/storage-file-share/?lang=original
项目主页：https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/storage/storage-file-share/README.md
源码仓库：https://github.com/Azure/azure-sdk-for-js

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：14.1 MB，948 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=22\.0\.0
- 运行依赖：14 个
- 首次发布：2019-10-31T06:40:48.992Z
- 最新版本发布：2026-09-24T18:23:19.416Z
- 近 30 天下载量：935563（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：530（近 12 个月 47 个）

## 中文简介

微软 Azure 存储 JavaScript - 文件

## 安装

```sh
npm install @azure/storage-file-share
```

也可以使用：`pnpm add @azure/storage-file-share`、`yarn add @azure/storage-file-share`、`bun add @azure/storage-file-share`

## README

# Azure 存储文件 共享 JavaScript 客户端库

Azure 文件在云中提供了完全管理的文件共享,通过行业标准服务器消息块(SMB)协议可以访问. Azure文件共享可以通过云或对Windows,Linux和macOS的前提部署同时挂载. 此外,Azure文件共享可以在使用Azure文件同步的Windows Servers上被缓存,以便在使用数据的附近快速访问.

这个工程在JavaScript中提供了一个客户端库,使得它易于消费Microsoft Azure文件存储服务.

使用此软件包中的客户端库 :

-   获取/设置文件服务属性
-   创建/ 列表/ 删除文件共享
-   创建/列表/删除文件目录
-   创建/读取/列表/更新/删除文件

> 说明: 此软件包先前以名称发布 `@azure/storage-file`。 。 。 . 现已更名为 `@azure/storage-file-share` 以更好地与即将到来的新软件包保持一致 为 Azure 存储文件 DataLake 提供一套一致的 API 用于在 Azure 上处理文件 .

密钥链接 :

-   [源代码](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/storage/storage-file-share)
-   [软件包( npm)](https://www.npmjs.com/package/@azure/storage-file-share/)
-   [API 参考文档](https://learn.microsoft.com/javascript/api/@azure/storage-file-share)
-   [产品文档](https://learn.microsoft.com/azure/storage/files/storage-files-introduction)
-   [样本](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/storage/storage-file-share/samples)
-   [Azure 存储文件 REST APIs](https://learn.microsoft.com/rest/api/storageservices/file-service-rest-api)

## 开始

### 目前得到支持的环境

-   [节点.js的LTS版本](https://github.com/nodejs/release#release-schedule)
-   Safari,Chrome,Edge,和Firefox的最新版本.

看我们的 [支助政策](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) 更多细节.

### 先决条件

-   一个 [Azure 订阅](https://azure.microsoft.com/free/)
-   A 类 [存储账户](https://learn.microsoft.com/azure/storage/common/storage-account-create)

### 安装软件包

为JavaScript安装Azure文件存储客户端库的首选方法是使用npm包管理器. 键入下列终端窗口:

```bash
npm install @azure/storage-file-share
```

### 认证客户端

Azure存储器支持几种认证方法. 为了与 Azure 存储文件共享服务互动, 您需要创建存储客户端实例 - `ShareServiceClient`, (中文(简体) ), `ShareClient`,或 `ShareDirectoryClient` 举个例子 见 [用于创建 `ShareServiceClient`](https://npmcn.com/package/%40azure/storage-file-share/#readme-create-the-share-service-client) 学习更多关于认证.

-   [共享密钥](https://npmcn.com/package/%40azure/storage-file-share/#readme-with-storagesharedkeycredential)
-   [共享访问签名](https://npmcn.com/package/%40azure/storage-file-share/#readme-with-sas-token)

### 兼容性

这个库与Node.js和浏览器兼容,并与LTS Node.js版本(QQ8.16.0)和Chrome,Firefox和Edge等最新版本进行验证.

#### 网络工人

这个库要求某些DOM对象在浏览器中使用时可以全局取用,而网页工人默认不会提供. 您需要多填这些, 才能让这个图书馆在网络工作人员中工作 .

详情请参见我们 [在网络工人中使用Azure SDK的文档](https://aka.ms/azsdk/js/web-workers)

此库依赖于在网络工人使用时需要加载外部多填充的 DOM API :

-   [`document`](https://developer.mozilla.org/docs/Web/API/Document)
-   [`DOMParser`](https://developer.mozilla.org/docs/Web/API/DOMParser)
-   [`Node`](https://developer.mozilla.org/docs/Web/API/Node)
-   [`XMLSerializer`](https://developer.mozilla.org/docs/Web/API/XMLSerializer)

#### 节点J和浏览器之间的差异

节点(Node.js)和浏览器运行时间有差异. 启动此库时, 请注意 API 或 标有 _"绝对是无处可逃"_ 或者说 _"绝对是活在丛生"_。 。 。 .

-   如果一个文件持有压缩数据 `gzip` 或者说 `deflate` 格式及其内容编码相应设定,下载行为在Node.js和浏览器之间有所不同. 在Node.js存储客户端会以压缩格式下载文件,而浏览器中的数据则会以去压缩格式下载.

##### 以下特性,界面,类或函数仅在Node.js中提供

-   基于账户名称和账户密钥的共享密钥授权
    -   `StorageSharedKeyCredential`
-   共享访问签名( SAS) 生成
    -   `generateAccountSASQueryParameters()`
    -   `generateFileSASQueryParameters()`
-   平行上传和下载. 请注意: `ShareFileClient.uploadData()` 可在Node.js和浏览器中找到.
    -   `ShareFileClient.uploadFile()`
    -   `ShareFileClient.uploadStream()`
    -   `ShareFileClient.downloadToBuffer()`
    -   `ShareFileClient.downloadToFile()`

##### 以下特性, 界面, 类或函数仅可用于浏览器

不详

### Java 脚本套装

要在浏览器中使用此客户端库,首先需要使用捆绑器. 关于如何做到这一点的详情,请参见我们 [捆绑文件](https://aka.ms/AzureSDKBundling)。 。 。 .

### (简体中文)

你需要设置 [跨欧林资源共享](https://learn.microsoft.com/rest/api/storageservices/cross-origin-resource-sharing--cors--support-for-the-azure-storage-services) 用于浏览器的存储账户规则。 到 Azure 门户网站和 Azure 存储探索器, 找到您的存储账户, 为 blob/ queue/ file/ table 服务创建新的 CORS 规则 .

例如,您可以按照 CORS 设置创建调试程序。 但请根据生产环境的要求,精心定制设置.

-   允许来源: \*
-   允许动词: DELETE, GET, HEAD, MERGE, POST, OPTIONS, PUT
-   允许的标题 : \*
-   已曝光标题 : \*
-   最大年龄(秒):86400

## 关键概念

以下组件及其相应的客户端库构成Azure存储文件共享服务:

-   这个 _存储账户_ a. 《公约》缔约方会议 `ShareServiceClient`
-   A 类 _文件共享_ 以a为代表 `ShareClient`
-   可选 _目录的分级_ 文件共享中,以 `ShareDirectoryClient` 实例
-   A 类 _文件_ 文件共享中, 大小可能不超过 1 TiB, 由 a 代表 `ShareFileClient`

## 实例

-   [导入软件包](https://npmcn.com/package/%40azure/storage-file-share/#readme-import-the-package)
-   [创建共享服务客户端](https://npmcn.com/package/%40azure/storage-file-share/#readme-create-the-share-service-client)
-   [在账户中列出股份](https://npmcn.com/package/%40azure/storage-file-share/#readme-list-shares-in-the-account)
-   [创建新共享和目录](https://npmcn.com/package/%40azure/storage-file-share/#readme-create-a-new-share-and-a-directory)
-   [创建 Azure 文件然后上传到它](https://npmcn.com/package/%40azure/storage-file-share/#readme-create-an-azure-file-then-upload-to-it)
-   [在目录下列出文件和目录](https://npmcn.com/package/%40azure/storage-file-share/#readme-list-files-and-directories-under-a-directory)
-   [下载一个文件并将其转换为字符串( Node.js)](https://npmcn.com/package/%40azure/storage-file-share/#readme-download-a-file-and-convert-it-to-a-string-nodejs)
-   [下载一个文件并转换为字符串( 浏览器)](https://npmcn.com/package/%40azure/storage-file-share/#readme-download-a-file-and-convert-it-to-a-string-browsers)

### 导入软件包

要使用客户端, 请导入软件包到您的文件中 :

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

替代品,有选择地仅导入所需的类型:

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

### 创建共享服务客户端

这个 `ShareServiceClient` 需要文件共享服务的URL和访问证书。 也可以选择接受 `options` 参数.

#### 使用连接字符串

或者,你可以即时 `ShareServiceClient` 使用 `fromConnectionString()` 以全连接字符串作为参数的静态方法。 (连接字符串可以从Azure门户网站获得

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

const connectionString = "<connection string>";

const shareServiceClient = ShareServiceClient.fromConnectionString(connectionString);
```

#### 与 `StorageSharedKeyCredential`

传入 `StorageSharedKeyCredential` 带有您的账户名称和账户密钥。 (账户名称和账户钥匙可从Azure门户网站获取. )

```ts
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 Token 连接

还有... 你可以即兴表演 `ShareServiceClient` 带有共享访问签名(SAS). 您可以从 Azure 端口获得 SAS 令牌或使用 `generateAccountSASQueryParameters()`。 。 。 .

```ts
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` 语法 :

```ts
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`数字 :

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

### 创建新共享和目录

```ts
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 文件然后上传到它

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

### 文件的列表范围

使用 `ShareFileClient.listRanges()` 以 pagized 方式列出文件的有效字节范围 无法同步。 每个项目均为 `ShareFileRange` 与 `start`, (中文(简体) ), `end`,以及 `isClear`启用 `ShareFileClient.listRangesDiff()` 列出自上次共享快照以来变化的区域; 返回已清除的区域 `isClear` 设置为 `true`。 。 。 .

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

使用 `.byPage()` 以控制页面大小,并从继续符中恢复:

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

### 在目录下列出文件和目录

使用 `DirectoryClient.listFilesAndDirectories()` 在文件和目录上行走, 与新的 `for-await-of` 语法. 这个 `kind` 属性可用于识别 iterm 是目录或文件.

```ts
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`数字 :

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

展期的完整样本请参见 [样本/v12/类型标注/批注/列表FilesAnd Directories.ts](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/storage/storage-file-share/samples/v12/typescript/src/listFilesAndDirectories.ts)。 。 。 .

### 下载一个文件并将其转换为字符串( Node.js)

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

### 下载一个文件并转换为字符串( 浏览器)

请参看 [Java 脚本套装](https://npmcn.com/package/%40azure/storage-file-share/#readme-javascript-bundle) 在浏览器中使用此库的更多信息.

```ts
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` 假设值为 [样本/v12/类型标记/src/shareSerivceClient.ts](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/storage/storage-file-share/samples/v12/typescript/src/shareServiceClient.ts)。 。 。 .

## 解决问题

允许伐木可能有助于发现有关失败的有用信息。 为了查看 HTTP 请求和回复的日志,设置 `AZURE_LOG_LEVEL` 环境变量改为 `info`。或者,可以在运行时拨打 `setLogLevel` 输入 `@azure/logger`数字 :

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

setLogLevel("info");
```

## 今后的步骤

更多代码样本

-   [文件共享存储样本( JavaScript)](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/storage/storage-file-share/samples/v12/javascript)
-   [文件共享存储样本( TypeScript)](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/storage/storage-file-share/samples/v12/typescript)
-   [文件共享存储测试例](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/storage/storage-file-share/test)

## 捐款

如果您想为图书馆捐钱 请读一下 [贡献指南](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) 学习如何构建和测试密码.

另见 [存储特定指南](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/storage/CONTRIBUTING.md) 关于为存储库设置测试环境的更多信息.

## 常见问题

### @azure/storage-file-share 是什么？

微软 Azure 存储 JavaScript - 文件

### 如何安装 @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 和提交记录判断。

