Create a Web App with Node.js
Node.js is the new hype for server-side webish things. It’s evented, non-blocking, fast and in javascript (not another language to learn, yay!). Real-Time Web is around the corner.
Javascript means you can use existing JS librairies. In this example I will use Mustache.js and Underscore to create the core of a minimal web application.
Let’s begin
I have 4 files: main.js, mustache.js, underscore.js, templates/index.html
We will put our code in main.js. First we require the things we’ll need:
Note that Underscore is CommonJS compliant so you don’t have to do anything for it. Then we add our actions which are composed by 3 things: URI, template name and the view.
We can create as many actions as we want. Now let’s create the server:
The server will be running but will not know how not handle actions. Let’s add a request listener:
The req variable contains the URI, so we will select the action corresponding to the request:
If the request doesn’t match an action, we will send an error:
In the other case we render the action:
We get the template content then renders it when the I/O process is complete. Here’s the template:
And that’s all! It’s running and you can create your blog with it for example.
There’s already a lot of Node.js frameworks that you can find on GitHub if you search for “node”. But there’s nothing really mature at this time.
Update (10 Feb 2010)
I forgot to mention that the mustache.js I’ve used was tweaked. We just have to add this following code at the end of the mustache.js file:
This will be merge into the main library in the near future and you can find the whole file here