Azure Storage JavaScript Client Library Sample for Queue Operations

In this sample, we will demonstrate common scenarios for Azure Queue Storage that includes creating, listing and deleting queues and messages.


Azure Storage queue service provides cloud messaging between application components. In designing applications for scale, application components are often decoupled, so that they can scale independently. Queue storage delivers asynchronous messaging for communication between application components, whether they are running in the cloud, on the desktop, on an on-premises server, or on a mobile device. Queue storage also supports managing asynchronous tasks and building process work flows.

Note: You may need set up a HTTP server to host this sample for IE browser, because IndexedDB is only available on websites with http or https URL schemes in IE. Azure Storage JavaScript Client Library currently depends on IndexedDB.

Contents:

Step 1: Preparing an Azure Storage account with CORS rules set

Cross-origin resource sharing, or CORS, must be configured on the Azure Storage account to be accessed directly from JavaScript in the browser. You are able to set the CORS rules for specific Azure Storage account on the Azure Portal. The "Allowed origins" could be set to "*" to allow all the origins in this sample. For more information about CORS, see Cross-Origin Resource Sharing (CORS).

Step 2: Importing Azure Storage JavaScript Client Library

Importing azure-storage.common.js and azure-storage.queue.js in your HTML file for queue operations, and make sure azure-storage.common.js is in front of azure-storage.queue.js.

<script src="azure-storage.common.js"></script>
<script src="azure-storage.queue.js"></script>

Step 3: Creating an Azure Storage Queue Service Object

The QueueService object lets you work with queues and messages. Following code creates a QueueService object with storage account and SAS Token.

var queueUri = 'https://' + 'STORAGE_ACCOUNT' + '.queue.core.windows.net';
var queueService = AzureStorage.createQueueServiceWithSas(queueUri, 'SAS_TOKEN');

In Azure Storage JavaScript Client Library, a global variable AzureStorage is the start point where we can create service objects for blob/table/queue/file and access to the storage utilities.

How to get full detailed API definitions? Currently, the JavaScript Client Library shares the same API definitions with Node.js SDK. Please check API details on Azure Storage Node.js API reference documents. The JavaScript global variable AzureStorage is just like the object require('azure-storage') returns in Node.js.
Warning: Azure Storage JavaScript Client Library also supports creating QueueService based on Storage Account Key for authentication besides SAS Token. However, for security concerns, we recommend use of a limited time SAS Token, generated by a backend web server using a Stored Access Policy.

Step 4: Queue Operations

Azure Queue storage is a service for storing large numbers of messages that can be accessed from anywhere in the world via authenticated calls using HTTP or HTTPS. A single queue message can be up to 64 KB in size, and a queue can contain millions of messages, up to the total capacity limit of a storage account.

List Queues

QueueService provides listQueuesSegmented and listQueuesSegmentedWithPrefix for retrieving the queue list under your storage account.

queueService.listQueuesSegmented(null, function (error, results) {
    if (error) {
        // List queue error
    } else {
        for (var i = 0, queue; queue = results.entries[i]; i++) {
            // Deal with queue object
        }
    }
});

Create Queue

QueueService provides createQueue and createQueueIfNotExists for creating a queue under a storage account.

queueService.createQueueIfNotExists('myqueue', function(error, result) {
    if (error) {
        // Create queue error
    } else {
        // Create queue successfully
    }
});

Delete Queue

QueueService provides deleteQueue and deleteQueueIfExists for deleting a queue under a storage account.

queueService.deleteQueueIfExists('myqueue', function(error, result) {
    if (error) {
        // Delete queue error
    } else {
        // Delete queue successfully
    }
});

Executable Example

The sample will try to create an Azure Storage queue service object based on SAS Token authorization. Enter your Azure Storage account name and SAS Token here. Make sure you have set the CORS rules for the Azure Storage queue service, and the SAS Token is in valid period.

Azure Storage queue service provides plenty of interfaces for queue operations. In following example, you can try to list all the queues under your storage account, and try to create or delete one queue from your account.

Step 5: Message Operations

A storage Message, in any format, of up to 64 KB. The maximum time that a message can remain in the queue is 7 days.

Note: Azure Storage JavaScript Client Library provides var encoder = new AzureStorage.QueueMessageEncoder.TextBase64QueueMessageEncoder() which is a Base64 encoder and docoder. If a message content string is encoded with encoder.encode(), remember to decode it with encoder.decode() after peek the message.

Peek Messages

QueueService provides peekMessage and peekMessages for retrieving the messages list under a queue.

queueService.peekMessages('myqueue', {numOfMessages: 32}, function (error, results) {
    if (error) {
        // Peek messages error
    } else {
        for (var i = 0, message; message = results[i]; i++) {
            // Deal with message object
        }
    }
});

Create Message

QueueService provides createMessage for creating a new message to a queue.

var encoder = new AzureStorage.QueueMessageEncoder.TextBase64QueueMessageEncoder();
queueService.createMessage('myqueue', encoder.encode('mymessage'), function (error, results, response) {
    if (error) {
        // Create message error
    } else {
        // Create message successfully
    }
});

Dequeue Message

QueueService provides getMessages and deleteMessage for dequeuing next message in a queue.

queueService.getMessages('myqueue', function(error, result, response) {
  if(!error){
    // Message text is in messages[0].messageText
    var message = result[0];
    queueService.deleteMessage('myqueue', message.messageId, message.popReceipt, function(error, response){
      if(!error){
        //message deleted
      }
    });
  }
});

Update Message

QueueService provides getMessages and updateMessage for updating next message in a queue.

var encoder = new AzureStorage.QueueMessageEncoder.TextBase64QueueMessageEncoder();
queueService.getMessages('myqueue', function(error, result, response) {
  if(!error){
    // Got the message
    var message = result[0];
    queueService.updateMessage('myqueue', message.messageId, message.popReceipt, 10, {messageText: encoder.encode('new text')}, function(error, result, response){
      if(!error){
        // Message updated successfully
      }
    });
  }
});

Executable Example

After clicked the "Select" button on the queue list in last step, you are able to operate with the queue messages under the selected queue.

Step 6: Creating your JavaScript Application based on Azure Storage JavaScript Client Library

You can view the source code of this sample for detailed reference.