你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
适用于 JavaScript 的 Azure 存储文件共享客户端库 - 版本 12.17.0
Azure 文件存储在云端提供完全托管的文件共享,这些共享可通过行业标准的服务器消息块 (SMB) 协议进行访问。 Azure 文件共享可由云或者 Windows、Linux 和 macOS 的本地部署同时装载。 此外,可以使用 Azure 文件同步将 Azure 文件共享缓存在 Windows Server 上,以加快访问速度(与在数据使用位置进行访问的速度相当)。
此项目以 JavaScript 提供客户端库,以便轻松使用 Microsoft Azure 文件存储服务。
使用此包中的客户端库可以:
- 获取/设置文件服务属性
- 创建/列出/删除文件共享
- 创建/列出/删除文件目录
- 创建/读取/列出/更新/删除文件
注意:此包以前以 名称
@azure/storage-file
发布。 它已重命名为@azure/storage-file-share
,以便更好地与即将推出的 Azure 存储文件 DataLake 的新包保持一致,并提供一组一致的 API,用于在 Azure 上使用文件。
关键链接:
入门
目前支持的环境
- LTS 版本的 Node.js
- 最新版本的 Safari、Chrome、Edge 和 Firefox。
有关更多详细信息,请参阅我们的支持政策。
先决条件
安装包
安装适用于 JavaScript 的 Azure 文件存储客户端库的首选方法是使用 npm 包管理器。 在终端窗口中键入以下内容:
npm install @azure/storage-file-share
验证客户端
Azure 存储支持多种方式进行身份验证。 若要与 Azure 存储文件共享服务交互,需要创建存储客户端的实例 ( ShareServiceClient
例如 、 ShareClient
或 ShareDirectoryClient
)。 若要详细了解身份验证,ShareServiceClient
请参阅创建 的示例。
- 共享密钥
- 共享访问签名
兼容性
此库与 Node.js 和浏览器兼容,并针对 lts Node.js 版本 (>=8.16.0) 和最新版本的 Chrome、Firefox 和 Edge 进行验证。
Web 辅助角色
此库要求某些 DOM 对象在浏览器中使用时全局可用,Web 辅助角色默认不提供这些 DOM 对象。 需要填充这些内容,使此库在 Web 辅助角色中正常工作。
有关详细信息,请参阅有关 在 Web 辅助角色中使用 Azure SDK for JS 的文档
此库依赖于以下 DOM API,这些 API 在 Web 辅助角色中使用时需要加载外部填充:
Node.js 和浏览器之间的差异
Node.js 和浏览器运行时之间存在差异。 开始使用此库时,请注意标记为 “仅在 NODE.JS RUNTIME 中可用” 或 “仅在浏览器中可用”的 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()
以下功能、接口、类或函数仅在浏览器中可用
不可用
JavaScript 捆绑包
若要在浏览器中使用此客户端库,首先需要使用捆绑程序。 有关如何执行此操作的详细信息,请参阅捆绑 文档。
CORS
如果需要为浏览器进行开发,则需要为存储帐户设置 跨域资源共享 (CORS) 规则。 转到Azure 门户并Azure 存储资源管理器,找到存储帐户,为 blob/队列/文件/表服务创建新的 CORS 规则 () 。
例如,可以创建以下 CORS 设置进行调试。 但请根据生产环境中的要求仔细自定义设置。
- 允许的来源: *
- 允许的谓词:DELETE、GET、HEAD、MERGE、POST、OPTIONS、PUT
- 允许的标头: *
- 公开的标头: *
- 最大期限 (秒) :86400
关键概念
以下组件及其相应的客户端库构成 Azure 存储文件共享服务:
- 存储帐户本身,由 表示
ShareServiceClient
- 存储帐户中的 文件共享 ,由 表示
ShareClient
- 文件共享中 目录的可选层次结构 ,由
ShareDirectoryClient
实例表示 - 文件共享中的 文件 ,其大小可能高达 1 TiB,由 表示
ShareFileClient
示例
- 导入包
- 创建共享服务客户端
- 列出帐户中的共享
- 创建新共享和目录
- 创建 Azure 文件,然后上传到其中
- 列出目录下的文件和目录
- 下载文件并将其转换为字符串 (Node.js)
- 下载文件并将其转换为字符串 (浏览器)
导入包
若要使用客户端,请将包导入文件:
const AzureStorageFileShare = require("@azure/storage-file-share");
或者,有选择地仅导入所需的类型:
const { ShareServiceClient, StorageSharedKeyCredential } = require("@azure/storage-file-share");
创建共享服务客户端
ShareServiceClient
需要文件共享服务的 URL 和访问凭据。 它还可以选择接受 参数中的 options
某些设置。
使用 连接字符串
或者,可以使用具有完整连接字符串作为参数的静态方法实例化 ShareServiceClient
fromConnectionString()
。 (可以从 azure 门户获取连接字符串。)
const { ShareServiceClient } = require("@azure/storage-file-share");
const connStr = "<connection string>";
const shareServiceClient = ShareServiceClient.fromConnectionString(connStr);
使用 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");
后续步骤
更多代码示例
贡献
若要为此库做出贡献,请阅读贡献指南,详细了解如何生成和测试代码。
有关为存储库设置测试环境的其他信息,请参阅特定于存储的 指南 。
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈