# 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 IE11 and latest Chrome.

## Contents:

- Step 1: Preparing an Azure Storage account with CORS rules set
- Step 2: Importing Azure Storage JavaScript Client Library
- Step 3: Creating an Azure Storage Queue Service Object
- Step 4: Queue Operations
- Step 5: Message Operations
- Step 6: Creating your JavaScript Application based on Azure Storage JavaScript Client Library

## 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.queue.js` in your HTML file for queue operations.

    <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.Queue.createQueueServiceWithSas(queueUri, 'SAS_TOKEN');

You can load Azure Storage JavaScript Client Library in a CommonJS or AMD environment by JavaScript module loaders. If no module system is found, global variable `AzureStorage.Queue` will be set, which is the start point where we can create service objects for queue and access to the storage utilities.

How to get full detailed API definitions? Currently, the JavaScript Client Library shares almost the same API definitions with Node.js SDK, besides Node.js runtime specific APIs. Please check API details on Azure Storage API reference documents. The JavaScript global variable `AzureStorage.Queue` is just like the object `require('azure-storage')` returns in Node.js, but limits to Queue related interfaces. Go to QueueService to view possible methods provided by `QueueService` class.
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.

Storage account: SAS Token:

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.

- Click
  button to view the queue list under your Azure Storage account

- Click
  button to create a queue under your Azure Storage account:

  New Queue Name:

- Click "Delete" button to delete the queue under your Azure Storage account

- Click "Select" button to select a queue and operate with the queue messages in next step

## 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.Queue.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.Queue.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.Queue.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.

- Click
  button to refresh the message list in your selected queue

- Click
  button to create a message in your selected queue:

  New Message Content:

- Click
  button to update the top queue message in your selected queue (Dequeued messages will be invisible for 30s by default.):

  Update Message Content:

- Click
  button to dequeue the top queue message in your selected queue:

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

1. Setting CORS rules for your selected Azure-Storage account queue service.
2. Including functional file(s) needed, such as "azure-storage.queue.js" for queue operation.
3. Using keyword "AzureStorage.Queue" to access to Azure storage JavaScript APIs for queues.
4. Referring to API documents for detailed API definitions.

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