Over a million developers have joined DZone.

Node.js in Azure Web Sites and Service Bus - Reading Messages from Cloud-hosted Queues

DZone 's Guide to

Node.js in Azure Web Sites and Service Bus - Reading Messages from Cloud-hosted Queues

· Cloud Zone ·
Free Resource

This post is about reading Service Bus Queues messages from Node.js.

  1. Creating the queues

  2. Populating the queues

  3. Downloading Web Matrix

  4. Setting up node

  5. Configuring Azure

  6. Writing Code

  7. Reading Service Bus Queues

  8. Testing it locally

The last blog post

  1. http://blogs.msdn.com/b/brunoterkaly/archive/2014/08/07/learn-how-to-create-a-queue-place-and-read-a-message-using-azure-service-bus-queues-in-5-minutes.aspx

Code to create and populate queue

Populate SB Queue
        NamespaceManager namespaceManager = NamespaceManager.Create();
        Console.WriteLine("\nCreating Queue '{0}'...", QueueName);
        // Delete if exists
        if (namespaceManager.QueueExists(QueueName))

Code to Define message type

Define Msg Type
  private static BrokeredMessage CreateSampleMessage(string messageId, string messageBody)
        BrokeredMessage message = new BrokeredMessage(messageBody);
        message.MessageId = messageId;
        return message;

Code to Write to queue

Write to Queue

Error recovery

Error Recovery
catch (MessagingException e)
    if (!e.IsTransient)
    // If we hit error, wait a couple of seconds and loop again
private static void HandleTransientErrors(MessagingException e)
        //If transient error/exception, let's back-off for 2 seconds and retry
        Console.WriteLine("Will retry sending the message in 2 seconds");

This post is about getting node to read service bus queue messages

The primary goal here is get node up and running and have a reasonable IDE to work with. Web Matrix is a great tool

Install Web Matrix


Figure 1: Installing Web Matrix

Installing Node

Let's get Node installed at the point. The download link for node is http://nodejs.org/


Figure 2: Installing Node.js on Windows

After installation

All the node files you will need are now find here c:\program files\nodejs

Starting web matrix and starting new project

We have already installed Web Matrix. It is time to start writing hello world. Select from the template gallery.

Select from Template Gallery

From the File menu, choose Site from Template Gallery


Figure 3: Web Matrix Template Gallery

Viewing the default project

You will need to provide a site name. An Azure Web Site will be provisioned for you. This will be where we deploy to once we are ready.


Figure 4: Defining An Azure Web Site

Getting your project's folder

If you right mouse click in the solution you can choose ?Show file in Explorer.? This allows you to easily navigate to the folder if you copy the path to your clipboard. We will navigate to our project folder so we can install the azure node packages. We will run the utility ?npm? which allows you to install new packages from the npm website directly into our node project from Web Matrix.


Figure 5: Getting to the project folder

The command line

The command line is where you will actually add the needed node packages.


Figure 6: The command line

Adjusting the path

You will need to fix your path to make sure the node executables are available.


Figure 7: Setting the Path

A simple NPM command

Note that we have some parameters available through NPM.


Figure 8: Using NPM

Install the Azure Package

Simply type in npm install azure


Figure 9: Installing the Azure Package

Verifying the package(s)

You can see below we have a number of modules installed. You can expand the node_modules folder to see what is installed.


Figure 10: Viewing the Package

Writing some node.js code

Now we can start writing the code for node.js.

One of the first things you will need is the connection string for your Service Bus connection. You can get this at the portal.

You can also get it from the portal as seen below.


Figure 11: Getting the Service Bus Connection String

Some Node.js code (server.js)

Here is some code to read messages from the Azure Service Bus Queue.

Main Example Code
var azure = require('azure');
var http = require('http');
var queue = 'samplequeue';
var error;
http.createServer(function (req, res) {
    var connString1 = 'Endpoint=sb://smartdoorqueue-ns.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=[get this from the portal]';
    // Crucial function call to get connected. Make sure  you have the proper
    // configuration with auzre to run
    serviceBusServiceClient = azure.createServiceBusService(connString1);
    console.log('create topic()');
    serviceBusServiceClient.createTopicIfNotExists('MyTopic3', function (error) {
        if (!error) {
            // Topic was created or exists
            console.log('topic created or exists.');
        else {
    // Helps with error tracking
    console.log('call receiveMessage()');
    // Get rid of output to browser for now
    //res.writeHead(200, { 'Content-Type': 'text/html' });
    //res.end('Hello, world 6!');
}).listen(process.env.PORT || 8081);
// Here is the code that will receive the first 2 messages in the queue.
function receiveMessages() {
  // Step 2: Receive the messages.
  serviceBusServiceClient.receiveQueueMessage(queue, true, function (error1, message1) {
    if (error1) {
    } else {
      serviceBusServiceClient.receiveQueueMessage(queue, true, function (error2, message2) {
        if (error2) {
        } else {
var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('Hello, world!');
}).listen(process.env.PORT || 8080);

Viewing the output from the messages in the queue

Now it is a simple case of running the code by hitting Run from the WebMatrix Toolbar. Here is what the output looks like:


Figure 13: Viewing Message from the Service Bus Queue


This is a simple post that illustrates how you can use Node.js to read messages from the Azure Service Bus.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}