DailyJS

Node Roundup: Express 2 Blowout

2011-03-16 00:00:00 +0000 by Alex R. Young

Express 2 and New Express Modules

As noted in Monday's Node
tutorial
, Express 2 is
getting close to release. The current version in npm is
express@2.0.0rc, so get ready!

There's an Express 1.x to 2.x migration
guide
to help you update your apps.
I don't think the changes are too drastic, but it's worth being aware of
them before migrating. To summarise:

Express Resource

TJ is also working on several new modules that make working with Express
potentially more convenient. If you want to work with REST resources,
take a look at
express-resource.

exports.index = function(req, res){
  res.send('forum index');
};

exports.new = function(req, res){
  res.send('new forum');
};

exports.create = function(req, res){
  res.send('create forum');
};

exports.show = function(req, res){
  res.send('show forum ' + req.params.id);
};

exports.edit = function(req, res){
  res.send('edit forum ' + req.params.id);
};

exports.update = function(req, res){
  res.send('update forum ' + req.params.id);
};

exports.destroy = function(req, res){
  res.send('destroy forum ' + req.params.id);
};

Express Namespace

Sometimes it's useful to hang routes or resources off a prefix --
imagine a blog or CMS with an administration area. A neat way of
handling this is through
express-namespace, which looks like this:

app.namespace('/forum/:id', function(){
  app.get('/(view)?', function(req, res){
    res.send('GET forum ' + req.params.id);
  });

  app.get('/edit', function(req, res){
    res.send('GET forum ' + req.params.id + ' edit page');
  });

  app.namespace('/thread', function(){
    app.get('/:tid', function(req, res){
      res.send('GET forum ' + req.params.id + ' thread ' + req.params.tid);
    });
  });

  app.del('/', function(req, res){
    res.send('DELETE forum ' + req.params.id);
  });
});

Express Messages

Every web app I've ever worked on has had flash messages, so why not use
express-messages to do it? It's loaded as a dynamic helper, and just needs a call to
messages() in a view.

Express Configuration

Express Configuration is
an asynchronous configuration module for Express. That means you could
use a database to store your app's configuration:

app.configure(function(done){
  redis.hmget('settings', function(err, obj){
    for (var key in obj) app.set(key, obj[key]);
    done();
  });
});

app.listen(3000);