你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
Azure 文件存储提供云中完全托管的文件共享,可通过行业标准服务器消息块 (SMB) 协议进行访问。 Azure 文件共享可由云或 Windows、Linux 和 macOS 的本地部署同时装载。 此外,可以使用 Azure 文件同步在 Windows Server 上缓存 Azure 文件共享,以便在使用数据的位置附近快速访问。
此项目在 JavaScript 中提供了一个客户端库,方便使用 azure 文件存储服务Microsoft。
使用此包中的客户端库可以:
- 获取/设置文件服务属性
- 创建/列出/删除文件共享
- 创建/列出/删除文件目录
- Create/Read/List/Update/Delete Files
注意:此包以前以名称
@azure/storage-file
发布。 它已重命名为@azure/storage-file-share
,以便更好地与即将推出的 Azure 存储文件 DataLake 的新包保持一致,并提供一组一致的 API 来处理 Azure 上的文件。
Key links:
Getting started
当前支持的环境
- LTS 版本的 Node.js
- Safari、Chrome、Edge 和 Firefox 的最新版本。
See our support policy for more details.
Prerequisites
安装包
安装适用于 JavaScript 的 Azure 文件存储客户端库的首选方法是使用 npm 包管理器。 在终端窗口中键入以下内容:
npm install @azure/storage-file-share
对客户端进行身份验证
Azure 存储支持多种方式进行身份验证。 若要与 Azure 存储文件共享服务交互,需要创建存储客户端的实例-ShareServiceClient
、ShareClient
或 ShareDirectoryClient
例如。 请参阅 示例,了解如何创建 ShareServiceClient
,了解有关身份验证的详细信息。
Compatibility
此库与 Node.js 和浏览器兼容,并针对 LTS Node.js 版本(>=8.16.0)和最新版本的 Chrome、Firefox 和 Edge 进行验证。
Web Workers
此库要求某些 DOM 对象在浏览器中使用时全局可用,Web 辅助角色默认不提供这些对象。 需要填充这些内容以使此库在 Web 辅助角色中正常工作。
有关详细信息,请参阅我们的 文档,了解如何在 Web 辅助角色中使用 Azure SDK for JS
此库依赖于以下 DOM API,这些 API 需要在 Web 辅助角色中使用时加载外部填充:
Node.js 和浏览器之间的差异
Node.js 和浏览器运行时之间存在差异。 开始使用此库时,请注意标有 “仅在NODE.JS运行时中可用”的 API 或类 或 “仅在浏览器中可用”。
- 如果文件保存
gzip
或deflate
格式的压缩数据,并且其内容编码设置相应,则下载行为在 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 Bundle
若要在浏览器中使用此客户端库,首先需要使用捆绑程序。 For details on how to do this, please refer to our bundling documentation.
CORS
如果需要为浏览器进行开发,则需要为存储帐户设置 跨域资源共享(CORS) 规则。 转到 Azure 门户和 Azure 存储资源管理器,找到存储帐户,为 Blob/队列/文件/表服务创建新的 CORS 规则。
例如,可以创建以下 CORS 设置进行调试。 但请根据生产环境中的要求仔细自定义设置。
- 允许的源: *
- 允许的谓词:DELETE、GET、HEAD、MERGE、POST、OPTIONS、PUT
- 允许的标头: *
- 公开的标头: *
- 最大年龄(秒):86400
Key concepts
以下组件及其相应的客户端库构成了 Azure 存储文件共享服务:
- The storage account itself, represented by a
ShareServiceClient
- A file share within the storage account, represented by a
ShareClient
- 文件共享中 目录的可选
层次结构,由 实例表示 - A file within the file share, which may be up to 1 TiB in size, represented by a
ShareFileClient
Examples
- 导入包
- 创建共享服务客户端
- 列出帐户 中的共享
- 创建新共享和目录
- 创建 azure 文件,然后将其上传到
- 列出目录下的文件和目录
- 下载文件并将其转换为字符串(Node.js)
- 下载文件并将其转换为字符串(浏览器)
导入包
若要使用客户端,请将包导入文件:
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 令牌
此外,还可以使用共享访问签名(SAS)实例化 ShareServiceClient
。 可以从 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++;
}
For a complete sample on iterating please see 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);
});
}
下载文件并将其转换为字符串(浏览器)
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
启用日志记录可能有助于发现有关故障的有用信息。 若要查看 HTTP 请求和响应的日志,请将 AZURE_LOG_LEVEL
环境变量设置为 info
。 或者,可以通过在 setLogLevel
中调用 @azure/logger
在运行时启用日志记录:
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
Next steps
更多代码示例
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.
另请参阅 存储特定指南,了解有关为存储库设置测试环境的其他信息。