Getting Acquainted with Node.js on Windows Azure

node.jsNode.js at its root is a command line tool that lets developers run JavaScript programs by typing node my_app.js.

Node provides a JavaScript application programming interface (API) for accessing the network and file system. It works well to develop scalable networked programs where low response times and high concurrency are important.

As with any technology, it’s good to understand where the technology has strengths and where it shines. My colleague Aaron Stannard shares his insights in Code Camp Talks: Intro to Node.JS and Building Web Apps with Express.

Good Scenarios

Node is good for high request volume, low response sizes. Good for publish/subscribe scenarios. Real-time applications.

Online games, message passing services, social networks, content-syndication services, chat, real time games.

Not So Good Scenarios

Large HTTP response sizes, CRUD, transaction-heavy systems.

Static file servers, reporting tools, blogs, content management, e-commerce.

Getting Started on Windows Azure, Node.js

The purpose of this blog post is to let you get acquainted with Node, give you some a way to get started, and an overview what it does well and how you can use it in your application development.

I’ll point you to the specific resources where you can dive in and learn more about each topic.

Getting Windows Azure, Node.js

Get Windows Azure

Next see the tutorial for Node.js on Windows Azure for the link on getting Node.js.

Tutorial for Hello World on Node.js

See a tutorial for Node.js on Windows Azure. You will learn:

  • How to get Node.js
  • How to create a new Windows Azure Node.js application using the Windows PowerShell tools.
  • How to run your Node application locally using the Windows Azure compute emulator
  • How to publish and re-publish your application to Windows Azure.

Quick Summary Of ‘Hello World’ on Node

1. Set Up the Development Environment. Install Node.js using WebPI.  You will have everything necessary to start developing. The following components are installed:

  • Node.js
  • IISNode
  • NPM for Windows
  • Windows Azure Emulators
  • Windows Azure Authoring Components
  • Windows Azure PowerShell for Node.js

2. Start PowerShell command prompt and create a shell of your Azure app. The tutorial at Node.js on Windows Azure explains the steps. As you use PowerShell your command window will look like this:

image

3. Edit server.js in Notepad or your favorite text editor. The default JavaScript looks like this:

 var http = require('http');
var port = process.env.port || 1337;
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello World\n');
}).listen(port);

In this code, if you want to use HTTP, you create HTTP and a port. Then use that HTTP object to create a server using an anonymous function. Inside the function you write out a head and ‘Hello World\n’. The server then listens to the ports for events.

req and res are passed into the function so you have access to the request and response objects.

request is an instance of http.ServerRequest which holds the properties about the client, holds session state, and passes client-data to request handlers.

response is an instance of http.ServerResponse holds the HTTP response stream and can be written in chunks.

This code is almost identical to the “Hello World” sample on the nodejs.org website, except:

  • The port has been changed to allow IIS to handle HTTP traffic on behalf of the application. IIS Node.js integration provides Node.js applications with a number of benefits when running on-premise or in Windows Azure, including: process management, scalability on multi-core servers, auto-update, side-by-side with other languages, etc.
  • Console logging has been removed.

4. You can run the application in the emulator typing the PowerShell command Start-AzureEmulator -launch

You will get a browser page that opens up with Hello World at the top of the page in the Azure emulator.

5. You publish the application to Windows Azure using the steps shown in the tutorial.

Structure of Node Project

Once you create the default project, you can create a folder for views, models, and helpers. This helps organize your application.

post.js is a user defined module for handling persistent data.

timestamp.js is a user-defined module for other stuff. You can also add a directory for until tests.

In my example, tasklist is the name of the root project. server.js is the name of the main entry point. Some files are created by the PowerShell scripts for deployment to Azure.

image

Modules

You can create a module in a file.

For example, to include a circle module, add this code to server.js:

 var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is '
           + circle.area(4));

This code adds a module called circle and then write the area of a circle to the console.

circle.js would be a model that could look like this:

 var PI = Math.PI;

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};

When you want a module to be an instance of some class, assign the desired export object to module.exports.

Routing Requests

You will no doubt want to route your requests to a particular module. To keep the code loosely coupled you can do something like this in its own module:

 var url = require("url");
 function start(route) {  
    function onRequest(req, res) {    
        var pathname = url.parse(req.url).pathname;

        route(pathname);

        response.writeHead(200, {"Content-Type": "text/plain"});    
        response.write("Hello World");    
        response.end(); 
     } 

     http.createServer(onRequest).listen(8888);  
     console.log("Server has started.");
}

exports.start = start;

When called from the server, this routes the request to the requested file.

Event-Driven Callbacks

Node.js is event-driven. The power is that Node processes requests asynchronously. It could be doing work in some other process when a new request comes in. So when something is requested, an callback function is called. We pass a method into a function, and the method uses this function to call back if an event related to the method occurs.

To learn more about it and for a gentle walkthrough, I started with The Node Beginner Book by Manuel Kiessling. He explains, “We create the server, and pass a function to the method creating it. Whenever our server receives a request, the function we passed will be called.

“We don't know when this is going to happen, but we now have a place where we can handle an incoming request.“

image

In the case of our Hello World example, when the callback is called and our onRequest() function gets triggered, two parameters are passed into it: req and res.

You can add your own code to handle the work of your application.

And More

You can learn about each of the objects and functions in the Node.js documentation. But here’s a quick list of what is available as part of Node:

Deploying with Cloud9

Cloud9 IDE provides a cross-platform, browser-based development environment. One of the features Cloud9 supports for Node.js projects is that you can directly deploy to Windows Azure from within the IDE. Cloud9 also integrates with the GitHub and BitBucket repository services, so it’s easy to share your project with others.

Using Cloud9, you can develop and deploy an application to Windows Azure from many modern browsers and operating systems, without having to install additional development tools or SDKs locally. The steps below are demonstrated using Google Chrome on a Mac.

Get started with Cloud9 on Windows Azure.

Node.js with Express

Once you have the basics down, Express provides important extensions to Node.js.

The Express (expressjs.com) module provides a web framework for building MVC applications. It provides APIs for processing HTTP requests and supports view template engines for generating HTTP responses. It also includes a various tools and add-ons required by MVC applications, including the ability to generate basic MVC scaffolding for a web application.

Node.js includes a minimal set of functionality in the core runtime. Developers often use 3rd party modules to provide additional functionality when developing a Node.js application.

In the tutorial, Node.js Web Application using Express, you will extend the application created in the Node.js Web Application tutorial by using modules.

And Still More

  • IISNode hosts Node applications on IIS as native modules, manages life-cycle of node.exe, and can load balance multiple node.exe processes.
  • Connect. Connect is a middleware framework for Node, shipping with over 18 bundled middleware and a rich selection of
    3rd-party middleware. These include logger, basic auth, json parser, cookie parser, directory listing, automatic querystring parser, a flexible error handler, and much more.
  • Socket.IO aims to make realtime apps possible in every browser and mobile device, blurring the differences between the different transport mechanisms. It's care-free realtime 100% in JavaScript.

Quick History

Microsoft joined Joyent and Ryan Dahl to make Windows a supported platform in Node.

Our first goal is to add a high-performance Input/Output Completion Port (IOCP) API to Node to give developers the same high-performance/scalability on Windows that Node is known for. The IOCP API performs multiple simultaneous asynchronous input/output operations.

At the end of this initial phase of the project, we will have official binary node.exe releases on nodejs.org, meaning that Node.js will run on Windows Azure, Windows 2008 R2, Windows 2008 and Windows 2003.

IOCP Concept

An input/output completion port object is created and associated with a number of sockets or file handles. When I/O services are requested on the object, completion is indicated by a message queued to the I/O completion port. A process requesting I/O services is not notified of completion of the I/O services, but instead checks the I/O completion port's message queue to determine the status of its I/O requests. The I/O completion port manages multiple threads and their concurrency.

Resources

 

Bruce D. KyleISV Architect Evangelist | Microsoft Corporation