I have been playing with Node.js recently. Mostly doing some small hobby projects. One of them needed server side badly, some of the cool features were not possible with the client side only web app.
I was thinking about using RoR, Asp.Net Mvc or NancyFX all of these frameworks suitable for the task. Then why Node ? Well, the answer is simple, FUN. There is a lot of hype around it. Community is very dynamic, lots of modules and extensions created on the daily basis. As a Passionate Developer, I also wanted to try something new. I can do .Net stuff at work and it is allways good to try something new and fresh.
Basic Node.js server
Let’s start with a very basic example, just to see the bare Node without the modules.
Node.js with express module
This was a really simple example. Sure you can write whole app like this, but there are modules that provide a nice layer of abstraction with all the the nasty details hidden. I have been using the express module. It is a nice web application framework.
- better wrappers to the request and response
- support for view-engines
- routing mechanism
- cookies manipulation
- basic authentication
- more ...
The express module is loaded into app object. It is then used to define the routings, accepting POST and GET verb. The syntax is quite simple. You provide the regexp which matches the route and a function that is executed when the request is matched. Function gives the access to the request and response wrappers.
- (/^(.+)$/ regexp is not the best one, it matches almost everything and has to be defined as the last route. Still it works ok and all the js, css files are being sent.
- __dirname is a global value containing the name of the main directory with the node script.