This article is part of the article series "Node.JS Modules You Should Know About."
<- previous article next article ->
node logo

Hello 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.

Sponsor this blog series!

Doing a node.js company and want your ad to appear in the series? The ad will go out to 14,000 rss subscribers, 7,000 email subscribers, and it will get viewed by thousands of my blog visitors! Email me and we'll set it up!

Enjoy!

If you love these articles, subscribe to my blog for more, follow me on Twitter to find about my adventures, and watch me produce code on GitHub!

This article is part of the article series "Node.JS Modules You Should Know About."
<- previous article next article ->

Comments

Simon Permalink
December 14, 2011, 22:09

Yes, I'm using Express for a couple of small web projects (nothing fancy), and finding it very useful.

On a related noted, I'd be interested in your opinion regarding the best modules for delivering static content, whether via Express or standard Node server. I've tried quite a few, and almost all of them have the same annoying defect - they use file extensions to guess MIME types, but don't match case correctly. Thus, a .jpg file is an image, while .JPG is unknown binary content. Easily fixed, but it's astonishing that none of them get this right...

Simon Permalink
December 15, 2011, 04:31

Hmm... actually, looking at the Express source, it's 'static' middleware seems to use an external 'mime' module that appears to cope with uppercase names correctly. I might have to have a closer look at that...

December 18, 2011, 14:10

Well, you can always fix it easily for the filetypes you need.

January 23, 2012, 13:18

Hi,

There is a typo in post request handling example:

app.**post**('/', function(req, res){
    console.log(req.body.foo);
    res.send('ok');
});
Luke Brady Permalink
September 15, 2012, 03:36

Thanks! This helped me get my first view working!

macy Permalink
October 23, 2013, 07:52

This post is truly inspirational. See my hermes birkin here.

macy Permalink
October 23, 2013, 07:52

This post is truly inspirational. See my hermes birkin here.

Bharath Bhat Permalink
November 29, 2014, 18:58

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications i have created few application in express module. And find all SBI Bank details of Chittor Dist on this site.

December 05, 2014, 20:22

Totally in love with your blog.Nicely explained and brilliant coding.
new year wishes 2 u.

Leave a new comment

(why do I need your e-mail?)

(Your twitter name, if you have one. (I'm @pkrumins, btw.))

Type the word "sandbox_294": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.

Advertisements