快速入门:适用于 JavaScript 的 Azure 队列存储客户端库 v12Quickstart: Azure Queue storage client library v12 for JavaScript

适用于 JavaScript 的 Azure 队列存储客户端库版本 12 入门。Get started with the Azure Queue storage client library version 12 for JavaScript. Azure 队列存储服务可存储大量消息供稍后检索和处理。Azure Queue storage is a service for storing large numbers of messages for later retrieval and processing. 请按照以下步骤安装程序包并试用基本任务的示例代码。Follow these steps to install the package and try out example code for basic tasks.

使用适用于 JavaScript 的 Azure 队列存储客户端库 v12 完成以下操作:Use the Azure Queue storage client library v12 for JavaScript to:

  • 创建队列Create a queue
  • 向队列添加消息Add messages to a queue
  • 查看队列中的消息Peek at messages in a queue
  • 更新队列中的消息Update a message in a queue
  • 从队列接收消息Receive messages from a queue
  • 从队列中删除消息Delete messages from a queue
  • 删除队列Delete a queue

其他资源:Additional resources:


设置Setting up

本部分逐步指导如何准备一个项目,使其与适用于 JavaScript 的 Azure 队列存储客户端库 v12 配合使用。This section walks you through preparing a project to work with the Azure Queue storage client library v12 for JavaScript.

创建项目Create the project

创建名为 queues-quickstart-v12 的 Node.js 应用程序。Create a Node.js application named queues-quickstart-v12.

  1. 在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为项目创建新目录。In a console window (such as cmd, PowerShell, or Bash), create a new directory for the project.

    mkdir queues-quickstart-v12
  2. 切换到新创建的 queues-quickstart-v12 目录。Switch to the newly created queues-quickstart-v12 directory.

    cd queues-quickstart-v12
  3. 创建名为 package.json 的新文本文件。Create a new text file called package.json. 此文件定义 Node.js 项目。This file defines the Node.js project. 将此文件保存到 queues-quickstart-v12 目录中。Save this file in the queues-quickstart-v12 directory. 下面是文件的内容:Here is the contents of the file:

        "name": "queues-quickstart-v12",
        "version": "1.0.0",
        "description": "Use the @azure/storage-queue SDK version 12 to interact with Azure Queue storage",
        "main": "queues-quickstart-v12.js",
        "scripts": {
            "start": "node queues-quickstart-v12.js"
        "author": "Your Name",
        "license": "MIT",
        "dependencies": {
            "@azure/storage-queue": "^12.0.0",
            "@types/dotenv": "^4.0.3",
            "dotenv": "^6.0.0"

    如果需要,可以在 author 字段中输入自己的名字。You can put your own name in for the author field, if you'd like.

安装包Install the package

当仍在 queues-quickstart-v12 目录中时,使用 npm install 命令安装适用于 JavaScript 包的 Azure 队列存储客户端库。While still in the queues-quickstart-v12 directory, install the Azure Queue storage client library for JavaScript package by using the npm install command.

npm install

此命令读取 package.json 文件,并安装适用于 JavaScript 包的 Azure 队列存储客户端库 v12 及其依赖的所有库。This command reads the package.json file and installs the Azure Queue storage client library v12 for JavaScript package and all the libraries on which it depends.

设置应用框架Set up the app framework

从项目目录中执行以下操作:From the project directory:

  1. 在代码编辑器中打开另一个新文本文件Open another new text file in your code editor

  2. 添加 require 调用以加载 Azure 和 Node.js 模块Add require calls to load Azure and Node.js modules

  3. 为程序创建结构,包括非常基本的异常处理Create the structure for the program, including very basic exception handling

    代码如下:Here's the code:

    const { QueueClient } = require("@azure/storage-queue");
    const uuidv1 = require("uuid/v1");
    async function main() {
        console.log("Azure Queue storage v12 - JavaScript quickstart sample");
        // Quick start code goes here
    main().then(() => console.log("\nDone")).catch((ex) => console.log(ex.message));
  4. 将新文件在 queues-quickstart-v12 目录中另存为 queues-quickstart-v12.js 。Save the new file as queues-quickstart-v12.js in the queues-quickstart-v12 directory.

从 Azure 门户复制凭据Copy your credentials from the Azure portal

当示例应用程序向 Azure 存储发出请求时,必须对其进行授权。When the sample application makes a request to Azure Storage, it must be authorized. 若要对请求进行授权,请将存储帐户凭据以连接字符串形式添加到应用程序中。To authorize a request, add your storage account credentials to the application as a connection string. 按照以下步骤查看存储帐户凭据:View your storage account credentials by following these steps:

  1. 登录 Azure 门户Sign in to the Azure portal.

  2. 找到自己的存储帐户。Locate your storage account.

  3. 在存储帐户概述的“设置”部分,选择“访问密钥”。 In the Settings section of the storage account overview, select Access keys. 在这里,可以查看你的帐户访问密钥以及每个密钥的完整连接字符串。Here, you can view your account access keys and the complete connection string for each key.

  4. 找到“密钥 1”下面的“连接字符串”值,选择“复制”按钮复制该连接字符串。 Find the Connection string value under key1, and select the Copy button to copy the connection string. 下一步需将此连接字符串值添加到某个环境变量。You will add the connection string value to an environment variable in the next step.

    显示如何从 Azure 门户复制连接字符串的屏幕截图

配置存储连接字符串Configure your storage connection string

复制连接字符串以后,请将其写入运行应用程序的本地计算机的新环境变量中。After you have copied your connection string, write it to a new environment variable on the local machine running the application. 若要设置环境变量,请打开控制台窗口,并遵照适用于操作系统的说明。To set the environment variable, open a console window, and follow the instructions for your operating system. <yourconnectionstring> 替换为实际的连接字符串。Replace <yourconnectionstring> with your actual connection string.


setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"

在 Windows 中添加环境变量后,必须启动命令窗口的新实例。After you add the environment variable in Windows, you must start a new instance of the command window.


export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"


export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

重新启动程序Restart programs

添加环境变量后,重启需要读取环境变量的任何正在运行的程序。After you add the environment variable, restart any running programs that will need to read the environment variable. 例如,重启开发环境或编辑器,然后再继续。For example, restart your development environment or editor before continuing.

对象模型Object model

Azure 队列存储是一个可存储大量消息的服务。Azure Queue storage is a service for storing large numbers of messages. 队列消息大小最大可为 64 KB。A queue message can be up to 64 KB in size. 一个队列可以包含数百万条消息,直至达到存储帐户的总容量限值。A queue may contain millions of messages, up to the total capacity limit of a storage account. 队列通常用于创建要异步处理的积压工作 (backlog)。Queues are commonly used to create a backlog of work to process asynchronously. 队列存储提供三种类型的资源:Queue storage offers three types of resources:

  • 存储帐户The storage account
  • 存储帐户中的队列A queue in the storage account
  • 队列中的消息Messages within the queue

以下图示显示了这些资源之间的关系。The following diagram shows the relationship between these resources.


使用以下 JavaScript 类与这些资源进行交互:Use the following JavaScript classes to interact with these resources:

  • QueueServiceClient:通过 QueueServiceClient 可管理存储帐户中的所有队列。QueueServiceClient: The QueueServiceClient allows you to manage the all queues in your storage account.
  • QueueClient:通过 QueueClient 类可管理和操纵单个队列及其消息。QueueClient: The QueueClient class allows you to manage and manipulate an individual queue and its messages.
  • QueueMessageQueueMessage 类表示在队列中调用 receiveMessages 时返回的各个对象。QueueMessage: The QueueMessage class represents the individual objects returned when calling receiveMessages on a queue.

代码示例Code examples

这些示例代码片段演示如何使用适用于 JavaScript 的 Azure 队列存储客户端库执行以下操作:These example code snippets show you how to do the following actions with the Azure Queue storage client library for JavaScript:

获取连接字符串Get the connection string

下面的代码从配置存储连接字符串部分中创建的环境变量中检索存储帐户的连接字符串。The code below retrieves the connection string for the storage account from the environment variable created in the Configure your storage connection string section.

main 函数内添加此代码:Add this code inside the main function:

// Retrieve the connection string for use with the application. The storage
// connection string is stored in an environment variable on the machine
// running the application called AZURE_STORAGE_CONNECTION_STRING. If the
// environment variable is created after the application is launched in a
// console or with Visual Studio, the shell or application needs to be
// closed and reloaded to take the environment variable into account.

创建队列Create a queue

确定新队列的名称。Decide on a name for the new queue. 以下代码将 UUID 值追加到队列名称,从而确保其是唯一的。The code below appends a UUID value to the queue name to ensure that it's unique.


队列名称只能包含小写字母、数字和连字符,并且必须以字母或数字开头。Queue names may only contain lowercase letters, numbers, and hyphens, and must begin with a letter or a number. 每个连字符的前后必须为非连字符字符。Each hyphen must be preceded and followed by a non-hyphen character. 名称的长度还必须介于 3 到 63 个字符之间。The name must also be between 3 and 63 characters long. 有关命名队列的详细信息,请参阅命名队列和元数据For more information about naming queues, see Naming Queues and Metadata.

创建 QueueClient 类的实例。Create an instance of the QueueClient class. 然后,调用 create 方法,以便在存储帐户中创建队列。Then, call the create method to create the queue in your storage account.

将此代码添加到 main 函数的末尾:Add this code to the end of the main function:

// Create a unique name for the queue
const queueName = "quickstart" + uuidv1();

console.log("\nCreating queue...");
console.log("\t", queueName);

// Instantiate a QueueClient which will be used to create and manipulate a queue
const queueClient = new QueueClient(AZURE_STORAGE_CONNECTION_STRING, queueName);

// Create the queue
const createQueueResponse = await queueClient.create();
console.log("Queue created, requestId:", createQueueResponse.requestId);

向队列添加消息Add messages to a queue

下面的代码片段调用 sendMessage 方法将消息添加到队列中。The following code snippet adds messages to queue by calling the sendMessage method. 它还保存从第三次 sendMessage 调用返回的 QueueMessageIt also saves the QueueMessage returned from the third sendMessage call. 返回的 sendMessageResponse 用于稍后在程序中更新消息内容。The returned sendMessageResponse is used to update the message content later in the program.

将此代码添加到 main 函数的末尾:Add this code to the end of the main function:

console.log("\nAdding messages to the queue...");

// Send several messages to the queue
await queueClient.sendMessage("First message");
await queueClient.sendMessage("Second message");
const sendMessageResponse = await queueClient.sendMessage("Third message");

console.log("Messages added, requestId:", sendMessageResponse.requestId);

查看队列中的消息Peek at messages in a queue

调用 peekMessages 方法来查看队列中的消息。Peek at the messages in the queue by calling the peekMessages method. peekMessages 方法从队列的前部检索一条或多条消息,但不会更改消息的可见性。The peekMessages method retrieves one or more messages from the front of the queue but doesn't alter the visibility of the message.

将此代码添加到 main 函数的末尾:Add this code to the end of the main function:

console.log("\nPeek at the messages in the queue...");

// Peek at messages in the queue
const peekedMessages = await queueClient.peekMessages({ numberOfMessages : 5 });

for (i = 0; i < peekedMessages.peekedMessageItems.length; i++) {
    // Display the peeked message
    console.log("\t", peekedMessages.peekedMessageItems[i].messageText);

更新队列中的消息Update a message in a queue

调用 updateMessage 方法来更新消息的内容。Update the contents of a message by calling the updateMessage method. updateMessage 方法可以更改消息的可见性超时和内容。The updateMessage method can change a message's visibility timeout and contents. 消息内容必须是最大为 64 KB 的 UTF-8 编码字符串。The message content must be a UTF-8 encoded string that is up to 64 KB in size. 除新内容外,还要在代码中传入之前保存的响应中的 messageIdpopReceiptAlong with the new content, pass in messageId and popReceipt from the response that was saved earlier in the code. sendMessageResponse 属性标识要更新的消息。The sendMessageResponse properties identify which message to update.

console.log("\nUpdating the third message in the queue...");

// Update a message using the response saved when calling sendMessage earlier
updateMessageResponse = await queueClient.updateMessage(
    "Third message has been updated"

console.log("Message updated, requestId:", updateMessageResponse.requestId);

从队列接收消息Receive messages from a queue

调用 receiveMessages 方法来下载以前添加的消息。Download previously added messages by calling the receiveMessages method. numberOfMessages 字段中,传入要为此调用接收的最大消息数。In the numberOfMessages field, pass in the maximum number of messages to receive for this call.

将此代码添加到 main 函数的末尾:Add this code to the end of the main function:

console.log("\nReceiving messages from the queue...");

// Get messages from the queue
const receivedMessagesResponse = await queueClient.receiveMessages({ numberOfMessages : 5 });

console.log("Messages received, requestId:", receivedMessagesResponse.requestId);

从队列中删除消息Delete messages from a queue

接收并处理消息后,从队列中删除消息。Delete messages from the queue after they're received and processed. 在本例中,“处理”即在控制台上显示消息。In this case, processing is just displaying the message on the console.

调用 deleteMessage 方法来删除消息。Delete messages by calling the deleteMessage method. 未显式删除的任何消息都将在队列中再次变为可见,以方便再一次进行处理。Any messages not explicitly deleted will eventually become visible in the queue again for another chance to process them.

将此代码添加到 main 函数的末尾:Add this code to the end of the main function:

// 'Process' and delete messages from the queue
for (i = 0; i < receivedMessagesResponse.receivedMessageItems.length; i++) {
    receivedMessage = receivedMessagesResponse.receivedMessageItems[i];

    // 'Process' the message
    console.log("\tProcessing:", receivedMessage.messageText);

    // Delete the message
    const deleteMessageResponse = await queueClient.deleteMessage(
    console.log("\tMessage deleted, requestId:", deleteMessageResponse.requestId);

删除队列Delete a queue

以下代码使用 delete 方法删除队列,从而清除该应用所创建的资源。The following code cleans up the resources the app created by deleting the queue using the delete method.

将此代码添加到 main 函数的末尾并保存文件:Add this code to the end of the main function and save the file:

// Delete the queue
console.log("\nDeleting queue...");
const deleteQueueResponse = await queueClient.delete();
console.log("Queue deleted, requestId:", deleteQueueResponse.requestId);

运行代码Run the code

此应用创建三条消息并将其添加到 Azure 队列。This app creates and adds three messages to an Azure queue. 此代码列出队列中的消息,然后检索并删除它们,最后删除队列。The code lists the messages in the queue, then retrieves and deletes them, before finally deleting the queue.

在控制台窗口中,导航到包含 queues-quickstart-v12.js 文件的目录,然后执行以下 node 命令来运行应用。In your console window, navigate to the directory containing the queues-quickstart-v12.js file, then execute the following node command to run the app.

node queues-quickstart-v12.js

应用的输出类似于以下示例:The output of the app is similar to the following example:

Azure Queue storage v12 - JavaScript quickstart sample

Creating queue...
Queue created, requestId: 5c0bc94c-6003-011b-7c11-b13d06000000

Adding messages to the queue...
Messages added, requestId: a0390321-8003-001e-0311-b18f2c000000

Peek at the messages in the queue...
         First message
         Second message
         Third message

Updating the third message in the queue...
Message updated, requestId: cb172c9a-5003-001c-2911-b18dd6000000

Receiving messages from the queue...
Messages received, requestId: a039036f-8003-001e-4811-b18f2c000000
        Processing: First message
        Message deleted, requestId: 4a65b82b-d003-00a7-5411-b16c22000000
        Processing: Second message
        Message deleted, requestId: 4f0b2958-c003-0030-2a11-b10feb000000
        Processing: Third message has been updated
        Message deleted, requestId: 6c978fcb-5003-00b6-2711-b15b39000000

Deleting queue...
Queue deleted, requestId: 5c0bca05-6003-011b-1e11-b13d06000000


在调试器中逐步执行代码,并在执行过程中反复检查 Azure 门户Step through the code in your debugger and check your Azure portal throughout the process. 检查存储帐户以验证是否已创建和删除队列中的消息。Check your storage account to verify messages in the queue are created and deleted.

后续步骤Next steps

在本快速入门中,你了解了如何使用 JavaScript 代码创建队列并向其添加消息。In this quickstart, you learned how to create a queue and add messages to it using JavaScript code. 然后,你了解如何查看、检索和删除消息。Then you learned to peek, retrieve, and delete messages. 最后,你还了解了如何删除消息队列。Finally, you learned how to delete a message queue.

有关教程、示例、快速入门和其他文档,请访问:For tutorials, samples, quick starts and other documentation, visit: