node logoHello everyone! This is the tenth post in my new node.js modules you should know about article series.

The first post was about dnode - the freestyle rpc library for node, the second was about optimist - the lightweight options parser for node, the third was about lazy - lazy lists for node, the fourth was about request - the swiss army knife of HTTP streaming, the fifth was about hashish - hash combinators library, the sixth was about read - easy reading from stdin, the seventh was about ntwitter - twitter api for node, the eighth was about socket.io that makes websockets and realtime possible in all browsers, the ninth was about redis - the best redis client API library for node.

Today I'm going to introduce you to express - an insanely fast and small server-side web development framework built on connect. Express is written by TJ Holowaychuk. TJ has written 85 node.js modules so far so expect many more of his modules in this series!

Check this out:

var express = require('express');

var app = express.createServer();

app.get('/', function(req, res){
    res.send('Hello World');
});

app.listen(3000);

This creates a web server that listens on port 3000 and handles the requests to /, returning Hello World string as a response.

Express has really powerful routing system. See this:

app.get('/user/:id', function(req, res){
    res.send('user ' + req.params.id);
});

This handles requests to /user/foo and automatically sets req.params.id to foo. You can also use regular expressions to handle routes.

If you want to handle POST requests, you have to make your app use bodyParser middleware. That can be done through app.use(express.bodyParser()). BodyParser basically parses the application/x-www-form-urlencoded and application/json request bodies and sets up req.body for you. For example:

app.use(express.bodyParser());

app.get('/', function(req, res){
    console.log(req.body.foo);
    res.send('ok');
});

This echos the body variables to console and sends back ok.

There are a bunch of different middlewares that you can use with express, such as:

app.use(express.logger(...));
app.use(express.cookieParser(...));
app.use(express.session(...));
app.use(express.static(...));
app.use(express.errorHandler(...));

The logger middleware handles logging of HTTP requests, cookieParser handles cookies, session handles HTTP sessions, static for static content, such as images, css and scripts, and errorHandler for handling exceptions and errors.

See the express documentation to learn more about middlewares.

Express also integrates with various templating engines. For example, my favorite templating language is jade (also written by TJ) and here is how you'd render a jade template with express:

app.get('/', function(req, res){
    res.render('index.jade', { title: 'My Site' });
});

Template filenames take the form <name>.<engine>, where <engine> is the name of the module that will be required. For example the template layout.ejs will tell express's view system to require('ejs'). The module being loaded must export the method exports.compile(str, options), and return a Function to comply with express.

Express features:

  • Robust routing.
  • Redirection helpers.
  • Dynamic view helpers.
  • Content negotiation.
  • Focus on high performance.
  • View rendering and partials support.
  • Environment based configuration.
  • Session based flash notifications.
  • High test coverage.
  • Executable for generating applications quickly.
  • Application level view options.

As well as:

  • Session support.
  • Cache API.
  • Mime helpers.
  • ETag support.
  • Persistent flash notifications.
  • Cookie support.
  • JSON-RPC.
  • Logging.

Also see this screencast on express by TJ:

For more examples see the examples directory in express source tree. Express also has awesome documentation.

You can install express through npm as always:

npm install express

Express on GitHub: https://github.com/visionmedia/express.