A CodeMash Session List with Node.js and Windows Azure

In early December, the Windows Azure team announced support for Node.JS on Windows Azure. In addition to being able to host your Node.js sites on Azure, they released a set of PowerShell scripts to make it easier to get started and a Node.js library for leveraging services on Windows Azure such as Table Storage, Blob Storage and Queues.

Last week at CodeMash, I had a chance to do some coding in Node.js and was impressed with how fast it was to go from a new project to have something running on Windows Azure. In this post, I’ll show you the steps I went through to create a very simple session viewing application.

Install Windows Azure PowerShell for Node.js

Getting started is really simple. Start by browsing to http://windowsauzre.com. Click the Developer tab and then select Node.js from the list. Clicking the Install button will launch the Web Platform Installer with the necessary packages selected. A few minutes later you’ll have everything you need to build your Node.js application.

SNAGHTML357192c_thumb3

Create your Node.js Application in PowerShell

The WindowsAzure.com site has some really great tutorials on creating a Node.js web application. You create the Azure project and then add a Web role to the project using the Windows Azure PowerShell for Node.js shortcut added to your start menu. The basic commands to execute are:

PS E:\src\demo> New-AzureService CodeMashJS
Service has been created at E:\src\demo\CodeMashJS
PS E:\src\demo\CodeMashJS> Add-AzureNodeWebRole Web
Role has been created at E:\src\demo\CodeMashJS\Web...

You now have a working Node.js application and can test it by executing the following:

PS E:\src\demo\CodeMashJS> Start-AzureEmulator -launch
Creating local package...
Starting Emulator...
Role is running at http://127.0.0.1:81
Started

image_thumb1

Adding Express.js to Your Web Role

Express.js is a popular Node.js package for doing web development. It provides a framework for separating your model, view and routing (controller) code and supports several view engines.

If you haven’t already, install Express.js globally using the Node.js Package Manager:

PS E:\src\demo\CodeMashJS> npm install –g Express

Now, you can execute the express command within your Web role directory. This will add a boilerplate set of code and views to your Web role using the Express.js framework.

PS E:\src\demo\CodeMashJS\Web> express .
destination is not empty, continue? Y
...
PS E:\src\demo\CodeMashJS\Web> npm install

If you look at the files in your Web role directory now, you’ll notice there is an app.js file created by Express and a server.js file created by Azure. Both of these files serve the same purpose – they are the root javascript files to be executed when you start your web server. The easiest thing to do at this point is to combine them into a single server.js file.

Copy the contents of app.js to server.js and add/modify the following highlighted lines of code:

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')

var app = module.exports = express.createServer();
var port = process.env.port || 1337;

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, 
                                 showStack: true })); 
});

app.configure('production', function(){
  app.use(express.errorHandler()); 
});

// Routes

app.get('/', routes.index);

app.listen(port);
console.log("Express server listening on port %d in %s mode", 
            app.address().port, app.settings.env);

After you’ve saved the new server.js file, go ahead and delete app.js as you won’t need it anymore. Refresh your browser (assuming you’re the Windows Azure emulator is still running from earlier).

image_thumb3

Retrieving, Formatting and Outputting Data

Now we can modify the default behavior in the files that Express.js created to retrieve, format and output the CodeMash session data. First, open up index.js in the routes folder. You’ll see the following code:

exports.index = function(req, res){
  res.render('index', { title: 'Express' })
};

Right now, this code just tells Express to render a view call index (located at views\index.jade). We need to change this so that it retrieves data from the CodeMash REST service and passes the result to the view.

To make retrieving the data a little easier, install the request package in your Web role using NPM:

npm install request

After this is installed, update index.js to match the following code:

var request = require('request');

exports.index = function(req, res){
  request('http://www.codemash.org/rest/sessions.json', 
    function (error, response, body) {
      if (!error) {
        sessionData = JSON.parse(body);
        res.render('index', { title: 'CodeMash Sessions', 
                              sessions: sessionData })
      };
    });
};

Now your code uses the request module to retrieve session data from CodeMash, evaluate the result and passes it into the index view as sessions.

To format the data into HTML, you can edit index.jade in the views directory. Jade is a template engine that uses a concise easy to read language for defining views. Below is Jade code for displaying the title, speaker and abstract for each session.

h1= title
ul
  - for session in sessions
    li
      strong= session.Title
      p Speaker: #{ session.SpeakerName }
      p= session.Abstract

You can test this by refreshing your browser. However, to get the Azure Emulator to restart your Node.js web server first open server.js and save it - this changes the time stamp on the file so Azure reloads the web server.

SNAGHTML3bd8317_thumb1

Deploying to Azure

Now that we have some basic functionality created, you can make your first deployment to Azure. The first thing you need to do is get your Azure Publish Settings file. From PowerShell, run Get-AzurePublishSettings. This will launch a browser to the Windows Azure site, where you can download and save locally the publish settings file. It doesn’t matter where you save it, but remember the location.

SNAGHTML3b4a42e_thumb1

Once you have your publish settings file, import it into your Azure project by executing the following command:

Import-AzurePublishSettings 'E:\codemashjs.publishsettings'

Finally, publish your service by executing Publish-AzureService.

That gets you started with a basic application. You can add more routes, views and functionality and rerun Publish-AzureService to push it our to Azure. We posted the code with additional functionality here.

Tags: Node.js, Windows Azure

blog comments powered by Disqus