Node.js App Basics - Part 1

02 Sep 2013

Feel free to review the other posts in this series:

==

Following up on yesterday’s post on getting started with Node.js, I’ll work through some of the basics for getting your first node.js web app running.

Please keep in mind that I’ve been in and out of node for about two years now, but have only recently done anything non-trivial with it. Chances are that you can find lots of guidance on Stack Overflow from people that have been working with node professionally, but they might also skip over some tidbits that are useful to those just getting their feet wet.

In this tutorial, we’ll use node.js to serve a front-end for the Wikipedia API and to search and display a single article abstract. I’m going to deliberately skip “best practices” in order to get us to a “fully working” version of this demo project. I will write a few follow up posts to outline how I’d do things in a professional situation afterwards.

I’m going to go ahead and assume you’ve got a terminal you’re happy with, and have already installed node.js/npm and it’s in your PATH. Let’s get started!

Create a new directory and cd into it:

$ mkdir wikipedia_front_end
$ cd wikipedia_front_end

The whole node world revolves around a file called “package.json”, fortunately, npm is great at helping you to get this configured:

$ npm init

This will ask you a series of questions about your app, you can choose your own values, and modify them as you wish at a later time. Keeping a package.json file will allow you to define packages and requirements for use when you want to deploy this project later.

While node.js ships with an http server that can handle incoming requests, the base server is very light-weight, and only does basic HTTP interactions. For anything more sophisticated, you’ll want to include some additional packages to make your life easier.

Node has a very popular package called “connect,” and this can be used to create a “pipeline” of actions that execute when a request is made to our application.

Standard things that usually happen in a web request include:

  • Form/cookie parsing
  • Logging
  • File serving
  • Authentication/Authorization
  • Custom server logic

connect provides some of this functionality, and a middleware infrastructure to allow us to do our own logic. Middleware was popularized by Ruby’s “rack” (and later copied by many frameworks).

If you’re not familiar with the middleware paradigm, the basic idea is that one can abstract an HTTP interaction down into two parts:

  1. An HTTP Request
  2. An HTTP Response

After these objects are created, a stack of middleware can be defined to interact with each of these two elements in a very elegant way:

function(request, response){
	/* Read information from the request and 
	then (optionally) manipulate the response. */
}

It is worth noting that middleware can read/modify both the request and the response, as well as having some side-effect (such as logging) that doesn’t modify either of these objects. (And there is a very important gotcha in node.js related to this that I will cover later on).

You could probably write your own middleware server in node in an afternoon, but connect includes some standard middleware that you’ll be happy to have, so let’s install it now:

$ npm install connect --save

The “–save” in this command causes the package requirements to be stored into package.json, which will allow them to be restored if you deployed to a service like heroku.

OK, so we’re just about to get our server going, here’s all the code you’ll need (save this to “server.js” in the “wikipedia_front_end” folder you created above):

//'require' says "pull in this installed package"
var connect = require('connect');

//we're still using Node's built in HTTP server, so let's pull it in.
var http = require('http');

//create our middleware stack (just send a basic message for now):
var app = connect()
	.use(function(request, response){
		response.write('Hello from connect!');
		response.end();
	});

//start a server on port 3000, any request that comes in should call
//the "app" function that is our middleware stack from above.
http.createServer(app).listen(3000);

Finally, in your terminal, type:

$ node server.js

This will start your server at http://localhost:3000. Navigate there to see the fruits of your labor. Note that you can go to any path on this server and the same response will be sent from node.

To stop this server, you can type “ctrl+c”, and this will end the node process.

If you’re like me, you may want to play at this point, you can certainly stop and start node after each modification “server.js”, but I have found that “supervisor” is a great utility to restart the server after each modification, you can install it like so:

$ npm install supervisor -g

This will install this command globally (that’s what the ‘-g’ does), so that you can use it from whichever projects you’re working on.

Let’s invoke the server again, but this time with supervisor:

$ supervisor server.js

You can now update and save changes to ‘server.js’ and supervisor will restart your app instantly, this will save you lots of time in development.

Next time, we’ll cover some important details about how the middleware works, and adding some custom server logic.