Search This Blog

Thursday, July 21, 2011

Self executing code in nodejs

Given that brackets against a function represent execute function:

var value = function blah(){return 'blah'}(); // evaluate value when called;

A nice way to start a web application with minimal start-up code is to wrap the execution of the start function in brackets - meaning execute this();

myWebApp.js:

var myWebApp = require('http');


(function start() {
    function onRequest(req, res) {
        res.writeHead(200, {"Content-Type": "text/plain"});
        res.write("Congratulations! my web app is running.");
        res.end();
    }
    myWebApp.createServer(onRequest).listen(8099);
    console.log("Started MyWebApp ...");
}());