Porting Django's urlpatterns to Node.js

I'm planning around (sic) with a new side project in the conceptual stage, and want to use Node.js to do it. (Mostly because it's so damn easy to deploy and doesn't hog resources when idle like my standard Apache2 and mod_wsgi configuration for deploying Django).

I was pretty pleased with the [configuration ideas presented in this blog entry][boldr], but wanted to bring in a bit more Django by porting over the [urlpatterns.py URL dispatching pattern][urlpatten]. It ended up being pretty easy.

Using the dispatcher it became possible to write a views.js file which takes extracted matches from regular expressions applied to URLs and passes them as functional parameters.

exports.index = function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('index.html');
    res.close();
};

exports.project = function(req, res, project) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('project.html: ' + project);
    res.close();
};

And here is the primary file which contains the pattern matcher and the dispatcher.

var http = require("http"),
    url = require("url"),
    views = require("./views"),
    port = 8000;
require("../underscore/underscore");

var patterns = [
    [/^\/project\/([\w-_])\/$/, views.project],
    [/^\/$/, views.index]
];

http.createServer(function(req, res) {
    req.addListener('end', function() {
        var path = url.parse(req.url).pathname,
            match = _.detect(patterns, function(pattern) {
                return pattern[0].exec(path);
            });
        if (match) {
            var p = [req, res].concat((match[0].exec(path)).slice(1));
            match[1].apply(this, p);
        } else {
            res.writeHead(404, {'Content-Type': 'text/html'});
            res.write('No matching pattern found');
            res.close();
        }
    });
}).listen(port);

All in all, a nice little setup. I'm playing around with Mu and maybe will release some kind of micro-framework tonight or tomorrow, albeit probably without much added value beyond what others have already invested time creating. Ah well.

All Rights Reserved, Will Larson 2007 - 2014.