Taking Toddler Steps with Node.js – Express

December 23rd, 2011

< The list of previous installments can be found here. >

There are several frameworks out there for building web applications with Node.js, one being more successful than the other. Express is probably the most popular and well known web development framework for Node.js. It’s heavily inspired by Sinatra and built on top of connect, which provides a middleware layer in order to easily add several capabilities and therefore extend your web application. As with most Node.js libraries, Express can be easily installed using npm.

npm install express

The following code snippet shows the most basic HTTP server example using Express:

var express = require('express');
var application = express.createServer();

application.get('/', function(request, response) {
    response.send('Hello Express!!');
});

application.listen(2455);

Notice that this doesn’t differ that much from most Node.js “Hello World” examples out there. So if we point our browser to localhost:2455, then the expected text message appears on the page. Now let’s add some middleware into the mix.

Suppose we want to serve some static content like HTML, CSS and/or JavaScript files. We can simply accomplish that by adding the following line of code.

application.use(express.static(__dirname + '/public'));

Now we simply have to add a new folder named “public” to the root folder of our application. In this folder we add an HTML file named “index.html” with the following content:

<html>
    <head>
        <title>Index</title>
    </head>
    <body>
        <h1>Hello Express!!</h1>
    </body>
</html>

Now we have to point our browser to localhost:2455/index.html and our static HTML file is served by Express. That’s how easy we can add capabilities to our web application. Express provides you with several built-in middleware like the one we just used in the last example, but there are also several other open-source middleware in the npm repository to choose from.

Middleware is usually added in a callback function that we provide with the configure method of the application object.

application.configure(function() {
    application.use(express.static(__dirname + '/public'));    
});

Express also provides the ability to configure middleware targeted for specific environments like development, staging, production, etc. … .

application.configure(function() {
    // Shared configuration
    application.use(express.bodyParser());
});

application.configure('development', function() {
    console.log('Configuring middleware for the development environment.');
    application.use(express.static(__dirname + '/public_on_development'));    
});

application.configure('staging', function() {
    console.log('Configuring middleware for the staging environment.');
    application.use(express.static(__dirname + '/public_on_staging'));    
});

application.configure('production', function() {
    console.log('Configuring middleware for the production environment.');
    application.use(express.static(__dirname + '/public'));    
});

Note that we can still provide a separate configuration function for shared configurations between different environments. When we start our web application in the staging environment, we just have to provide the NODE_ENV environment variable.

NODE_ENV=staging nodemon app.js

Now only the global configure function and the one for the staging environment are called.

Express also provides an executable for generating boilerplate code and setting up a basic web application. This is probably the quickest way to get up and running with Express.

node_modules/express/bin$ ./express –h

Usage: express [options] [path]

Options:

  -s, –sessions                  add session support

  -t, –template <engine>  add template <engine> support (jade|ejs). default=jade

  -c, –css <engine>          add stylesheet <engine> support (stylus). default=plain css

  -v, –version                    output framework version

  -h, –help                        output help information

So when I run the express executable with the default options, I get the following output:

./express /home/my_user/my_sample_app

create : /home/my_user/my_sample_app

create : /home/my_user/my_sample_app/package.json

create : /home/my_user/my_sample_app/app.js

create : /home/my_user/my_sample_app/public

create : /home/my_user/my_sample_app/views

create : /home/my_user/my_sample_app/views/layout.jade

create : /home/my_user/my_sample_app/views/index.jade

create : /home/my_user/my_sample_app/routes

create : /home/my_user/my_sample_app/routes/index.js

create : /home/my_user/my_sample_app/public/javascripts

create : /home/my_user/my_sample_app/public/images

create : /home/my_user/my_sample_app/public/stylesheets

create : /home/my_user/my_sample_app/public/stylesheets/style.css

don’t forget to install dependencies:

$ cd /home/my_user/my_sample_app && npm install

A package.json file is created for dependent modules, along with a public folder for JavaScript files and CSS stylesheets and even separate folders for views and routes. This is how the generated app.js file looks like:  

/**
 * Module dependencies.
 */

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

var app = module.exports = express.createServer();

// 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(3000);
console.log("Express server listening on port %d in %s mode", 
       app.address().port, 
       app.settings.env);

As you can see, it’s very easy to get started with Express and adding more capabilities to your web application as you go along. Make sure to watch this short screencast in order to get up and running in no time.

I’m planning to put out a couple more blog posts on Express and some very useful middleware that you can use for your applications. So stay tuned.

Until next time.

  • http://usb3gvn.com USB 3G

    We hope that you find this information useful and look forward to assisting you in the future. Thank for this support.