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 上处理文件 .
密钥链接 :
开始
目前得到支持的环境
- 节点.js的LTS版本
- Safari,Chrome,Edge,和Firefox的最新版本.
看我们的 支助政策 更多细节.
先决条件
安装软件包
为JavaScript安装Azure文件存储客户端库的首选方法是使用npm包管理器. 键入下列终端窗口:
npm install @azure/storage-file-share
认证客户端
Azure存储器支持几种认证方法. 为了与 Azure 存储文件共享服务互动, 您需要创建存储客户端实例 - ShareServiceClient, (中文(简体) ), ShareClient,或 ShareDirectoryClient 举个例子 见 用于创建 ShareServiceClient 学习更多关于认证.
兼容性
这个库与Node.js和浏览器兼容,并与LTS Node.js版本(QQ8.16.0)和Chrome,Firefox和Edge等最新版本进行验证.
网络工人
这个库要求某些DOM对象在浏览器中使用时可以全局取用,而网页工人默认不会提供. 您需要多填这些, 才能让这个图书馆在网络工作人员中工作 .
详情请参见我们 在网络工人中使用Azure SDK的文档
此库依赖于在网络工人使用时需要加载外部多填充的 DOM API :
节点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 脚本套装
要在浏览器中使用此客户端库,首先需要使用捆绑器. 关于如何做到这一点的详情,请参见我们 捆绑文件。 。 。 .
(简体中文)
你需要设置 跨欧林资源共享 用于浏览器的存储账户规则。 到 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
实例
- 导入软件包
- 创建共享服务客户端
- 在账户中列出股份
- 创建新共享和目录
- 创建 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 Token 连接
还有... 你可以即兴表演 ShareServiceClient 带有共享访问签名(SAS). 您可以从 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`);
文件的列表范围
使用 ShareFileClient.listRanges() 以 pagized 方式列出文件的有效字节范围
无法同步。 每个项目均为 ShareFileRange 与 start, (中文(简体) ), end,以及 isClear启用
ShareFileClient.listRangesDiff() 列出自上次共享快照以来变化的区域;
返回已清除的区域 isClear 设置为 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}`);
}
使用 .byPage() 以控制页面大小,并从继续符中恢复:
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 是目录或文件.
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++;
}
展期的完整样本请参见 样本/v12/类型标注/批注/列表FilesAnd Directories.ts。 。 。 .
下载一个文件并将其转换为字符串( 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()}`);
}
下载一个文件并转换为字符串( 浏览器)
请参看 Java 脚本套装 在浏览器中使用此库的更多信息.
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。 。 。 .
解决问题
允许伐木可能有助于发现有关失败的有用信息。 为了查看 HTTP 请求和回复的日志,设置 AZURE_LOG_LEVEL 环境变量改为 info。或者,可以在运行时拨打 setLogLevel 输入 @azure/logger数字 :
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
今后的步骤
更多代码样本
捐款
如果您想为图书馆捐钱 请读一下 贡献指南 学习如何构建和测试密码.
另见 存储特定指南 关于为存储库设置测试环境的更多信息.