I heart Node.js

March 10th, 2010

Node.js is one of the most intriguing projects I’ve seen in a while. For some reason, I’ve never truly enjoyed programming until I started programming in JavaScript. I did the usual BASIC programming as a freshman in high school, and actually tried learning C a bit earlier when I was 12 (let’s just say it didn’t go over well, except that I did win a C “competition” in high school based on that knowledge).

But when I could start hooking up my designs to really cool functionality, such as dmMonocle, my jQuery plugin for viewing images, I loved the combination that was possible. I could not only make beautiful designs, I could make beautiful web applications. My code could react to the actions of users — or in JavaScript lingo, the events of users.

Server side JS?

I’ve since learned to branch out, and have an affection for Python as well at this point! But I’m still in that weird designer/front end dev gray area, so I don’t get as much Python time as I’d like. However, with the advent of Node.js, I can now do some pretty awesome server side stuff in my favorite language. That’s right, you heard me: JavaScript is going server side — and even further in the future! Here’s the code I wrote to implement a very simple web server with Node.JS:

var fs = require('fs'),
    sys = require('sys'), 
    http = require('http');
    
// Simple Server Function
// Pulls the url of the request and responds with the appropriate HMTL file
// If no HTML file found in the request url, returns a 404 error. Boosh!
    
http.createServer(function (req, res) {
    
    var HTML;
    
    if(req.url.search(/\.html$/) > -1) { // Searches to see if the URL entered by the user ends in .html
        fs.readFile('../' + req.url, encoding='utf8', function(err, data) { // If it does, it tries to read the file
            if (err) { // Oh noes! The file doesn't exist! 404-butter time!
                _404(err);
            } else {
                HTML = data;
                res.writeHead(200, {'Content-Type': 'text/html'});
                res.write(HTML);
                res.close();
            }
        });
    } else { // Hey, they didn't enter a valid URL! You know what that means -- 404 BUTTER TIME!
       _404();
    }
    
    function _404(err) {
        if (err) sys.log(err);
        fs.readFile('../404.html', encoding='utf8', function(err, data) {
           HTML = data;
           res.writeHead(200, {'Content-Type': 'text/html'});
           res.write(HTML);
           res.close();
        });
    }
    
}).listen(8080); // Listen on port 8080
sys.puts("Brian's HTML Server running at http://127.0.0.1:8080/"); // Output a string to STDOUT (the command line in most cases)

Lame, but WTF is require()?

Now, this server isn’t very durable. For example, the html files have to be one directory down from the node server — not awesome, and it serves no CSS. But it was just a simple test script I wrote in 5 minutes to see what could be done with Node, and was a heck of a lot of fun. It also introduced me to the CommonJS project, and their implementation of modules. First of all, the CommonJS project aims to produce a common spec for server-side and application-building JavaScript — i.e. JavaScript’s not just for browsers anymore!

Now on to modules: at the top of the code, you’ll see I’m declaring 3 variables, all of which call a require() function. That require function is an example of the CommonJS module implementation, a way for JavaScript to pull in the contents from another file in a similar fashion to Python’s import or Ruby’s require.

The way of the future?

Pretty cool stuff for a few minutes of compilation time, reading through the Node.JS API (which only takes about 45 minutes even if you’re slow like me), and then getting a little dirty — and by that, I mean not dirty at all.

There’s some real potential here, and I’m going to take some time to play around with Express. It’s a Node.JS web framework inspired by a Sinatra, a Ruby web framework. Sinatra is another intriguing piece of software, and combined with HAML and SASS, two great technologies for rapidly developing HTML and CSS, it’s a very nice package indeed. Express seems to have adopted those parts of Sinatra, and should be just a grand old time to tinker with.