若要以编程方式访问 Azure 服务,请使用适用于 JavaScript 的 Azure 客户端库。 通常,这些库的范围是 microsoft1es 发布的 @azure npm 包范围。
客户端库和 REST API 之间的差异
使用以下信息了解何时使用哪种类型的访问。
- Azure 客户端库是访问 Azure 服务的首选方法。 这些库抽象化了管理基于云的 Azure 平台 REST 请求(例如身份验证、重试和日志记录)所需的样板代码。
- 如果采用以下方法,则 Azure REST API 是首选方法:
- 使用没有 Azure 客户端库的预览服务。 将代码视为预览版,在客户端库正式发布服务时,应更新该代码。
- 想要直接进行 REST 调用,因为不希望整个 SDK 使用单个 REST API,或者希望更深入地控制 HTTP 请求。
Azure 客户端和管理库
Azure 客户端库 版本 如下:
-
管理:使用管理库可以创建和管理 Azure 资源。 可以通过它们的包名称中的
arm-识别这些库。arm术语指示 Azure 资源管理器。 -
客户端:给定 Azure 资源已存在,请使用客户端库使用它并与之交互。
- 每个包 README.md 都包含文档和示例。
安装 Azure npm 包
可从 NPM 和 Yarn 免费获取 Azure 客户端库。 根据需要安装单个 SDK。 每个 SDK 都提供 TypeScript 定义。
在客户端或浏览器环境下,需要将 Azure 客户端库添加到 打包 过程。
使用 Azure npm 包示例代码
每个包都包含用于快速开始使用包的文档。 请参阅您使用的特定包的文档,以了解如何使用它们。
提供身份验证凭据
Azure 客户端库需要凭据 才能向 Azure 平台进行身份验证。 @azure/identity 提供的凭据类提供了以下几个优势:
- 快速加入
- 最安全的方法
- 将身份验证机制与代码分开。 这允许在本地和 Azure 平台上使用相同的代码,而凭据不同。
- 提供链接式身份验证,以便可以使用多种机制。
创建 SDK 客户端和调用方法
以编程方式创建凭据后,将凭据传递给 Azure 客户端。 客户端可能需要其他信息,例如订阅 ID 或服务终结点。 这些值可在 Azure 门户中供你的资源使用。
下面的代码示例使用 DefaultAzureCredential 客户端 @azure/arm-resources 库列出此凭据有权读取的资源组。
import { DefaultAzureCredential } from "@azure/identity";
import { ResourceManagementClient } from "@azure/arm-resources";
const subscriptionId = process.env.AZURE_SUBSCRIPTION_ID!;
if (!subscriptionId) {
throw new Error("AZURE_SUBSCRIPTION_ID environment variable is not set.");
}
console.log(`Using Subscription ID: ${subscriptionId}`);
async function main() {
const credential = new DefaultAzureCredential();
const client = new ResourceManagementClient(credential, subscriptionId);
let i=0;
for await (const item of client.resourceGroups.list()) {
console.log(`${++i}: ${item.name}`);
}
console.log(`Found ${i} resource group(s).`);
}
main().catch((err) => {
console.error(err);
});
结果异步分页
SDK 方法可以返回异步迭代器 PagedAsyncIterableIterator,以允许异步结果。 结果可能会使用分页标记和续页标记来分割结果集。
以下 JavaScript 示例 演示了异步分页。 代码将分页大小人为地设为2,以便在调试模式下运行示例代码时快速直观地演示该过程。
const { BlobServiceClient } = require("@azure/storage-blob");
const blobAccountConnectionString = "REPLACE-WITH-YOUR-STORAGE-CONNECTION-STRING";
const blobAccountContainerName = "REPLACE-WITH-YOUR-STORAGE-CONTAINER-NAME";
const pageSize = 2;
const list = async () => {
console.log(`List`);
let continuationToken = "";
let currentPage = 1;
let containerClient=null;
let currentItem = 1;
// Get Blob Container - need to have items in container before running this code
const blobServiceClient = BlobServiceClient.fromConnectionString(blobAccountConnectionString);
containerClient = blobServiceClient.getContainerClient(blobAccountContainerName);
do {
// Get Page of Blobs
iterator = (continuationToken != "")
? containerClient.listBlobsFlat().byPage({ maxPageSize: pageSize, continuationToken })
: containerClient.listBlobsFlat().byPage({ maxPageSize: pageSize });
page = (await iterator.next()).value;
// Display list
if (page.segment?.blobItems) {
console.log(`\tPage [${currentPage}] `);
for (const blob of page.segment.blobItems) {
console.log(`\t\tItem [${currentItem++}] ${blob.name}`);
}
};
// Move to next page
continuationToken = page.continuationToken;
if (continuationToken) {
currentPage++;
}
} while (continuationToken != "")
}
list(() => {
console.log("done");
}).catch((ex) =>
console.log(ex)
);
详细了解 Azure 上的分页和迭代器:
长时间运行的操作
SDK 方法可以返回长时间运行的操作(LRO)的原始响应。 此响应包括以下信息:
- 请求已完成
- 请求仍在处理中
以下 JavaScript 示例 演示了如何在.pollUntildone()等待 LRO 完成后再继续。
const { BlobServiceClient } = require("@azure/storage-blob");
const blobAccountConnectionString = "REPLACE-WITH-YOUR-STORAGE-CONNECTION-STRING";
const blobAccountContainerName = `test-${Date.now().toString()}`;
const files = [
{
"url": "https://github.com/Azure/azure-sdk-for-js/blob/main/README.md",
"fileName": "README.md"
},
{
"url": "https://github.com/Azure/azure-sdk-for-js/blob/main/gulpfile.ts",
"fileName": "gulpfile.ts"
},
{
"url": "https://github.com/Azure/azure-sdk-for-js/blob/main/rush.json",
"fileName": "rush.json"
},
{
"url": "https://github.com/Azure/azure-sdk-for-js/blob/main/package.json",
"fileName": "package.json"
},
{
"url": "https://github.com/Azure/azure-sdk-for-js/blob/main/tsdoc.json",
"fileName": "tsdoc.json"
},
];
const upload = async() => {
// get container client
const blobServiceClient = BlobServiceClient.fromConnectionString(blobAccountConnectionString);
// get container's directory client
const containerClient = blobServiceClient.getContainerClient(blobAccountContainerName);
files.forEach(async(file) =>{
await (
await containerClient
.getBlobClient(file.fileName)
.beginCopyFromURL(file.url)
).pollUntilDone();
})
}
upload(() => {
console.log("done");
}).catch((ex) =>
console.log(ex)
);
详细了解 Azure 上长时间运行的操作。
取消异步操作
@azure/abort-controller 包提供 AbortController 和 AbortSignal 类。 使用 AbortController 创建 AbortSignal,然后可以传递给 Azure SDK 以取消未完成的工作。 “Azure SDK” 的操作可以是:
- 根据自己的逻辑中止
- 因超时限制而中止
- 基于父任务信号的中止
- 根据父任务的信号 或 超时限制中止
了解详细信息:
- 如何使用中止信号取消 Azure SDK for JavaScript/TypeScript 中的操作
SDK 的详细日志记录
使用 Azure SDK 时,有时可能需要调试应用程序。
若要在 生成时启用日志记录,请将AZURE_LOG_LEVEL环境变量设置为
info。若要在 运行时启用日志记录,请使用 @azure/logger 包:
import { setLogLevel } from "@azure/logger"; setLogLevel("info");
捆绑
了解如何与 Azure SDK 捆绑: