Build a real application with node.js
We’ve seen in a previous article an introduction to node.js. However if you’ve read that article, you probably thought “what the heck will I do that ? My code won’t be readable”.
And I agree. That’s not readable and it’ll quickly become impossible to maintain on big applications.
In order to use the required libraries, we’ll one of the node’s packages managers, npm.
Installation is rather simple :
curl http://npmjs.org/install.sh | sudo sh
Connect is the equivalent of rack for node. Applications can go around it as middlewares, allowing us to manipulate the application at any level.
Let’s install Connect ! For that, we’ll use npm.
npm install connect
And let’s roll !
The standard Hello World of Connect, based from the documentation is the following :
We don’t even manage the current uri (we’d need for that, to do a if. I don’t advise for it). But we can quite easily sent text content. We’ve just created our first middleware.
Let’s continue with npm.
npm install express
Who said computers are complicated ? ;)
Right here, node becomes really interesting. With Express, we will finally start to create maintanables applications. Here’s our Hello World with Express :
We define a route on the / uri, which will give us the content “Hello World”. Any other URI will give us a 404.
Of course we can define as many URIs as we want with the get/post/put/delete methods.
By default, Express uses haml to manage the views. We’ll create a views folder with two files :
That file will be automatically included as our application’s layout. Add it your design.
That’s our index page’s file.
Restart your server, reload the page and admire your beautiful template parsed in html and displayed !
Now we can display our templates as we wich, we only need to add a bit of style to the page. For that, we’ll add a static CSS file.
Express manages them natively.
Any file located in the directory we’ll specify and which doesn’t correspond to an already defined route will then be displayed.
Let’s configure it. Before the
app.listen(300). aadd the following line :
app.use(express.staticProvider(__dirname + '/public'));
Then we tell Express to use the /public folder to display the static files. Create the file /public/style.css and include it in our layout :
You just have to add some style to your CSS.
Because of it’s relatively youth, node still evolves quite quickly. And Express is a proof of that. Several month ago, build a big application only with node was something we couldn’t even think of.
Today, even if Express offers only a quite low layer, it already allows to program way better applications than with a raw node.
Node still has a lot of surprises for us. The three coming years will be very exciting there.