With a colleague I was talking about Node.js. My first though, “yeah right, JavaScript on the server!”. But you have to be open minded if you want to learn new stuff. Therefore I thought about giving it a spin. I started looking for resources on the web, read a few of them and ended up at the article : express-mongo. This article was the beginning of my Node.js journey.

In this blog item I want to show you the steps I took, the resources I found useful and some improvements to the article that seems a bit outdated. It is not an explanation of what Node.js is, but it does provide some help to get started on your own.


The source

I took the sources from the article of Ciaran Jessup as my basis. So a lot of credits go to him. You can find my sources over at github:

https://github.com/jettro/nodejstryout

Setting up my environment

If you want to do something with nodejs, you have to install it first. I used MacPorts to install it, but lots of other ways are documented on the wiki. Using MacPorts all you have to do is:

sudo port install nodejs

The next step is to install a package manager. The mentioned article uses kiwi, but the node.js documentation recommends npm. Therefore I chose to use npm as well. Installing npm is documented well on the website: https://github.com/isaacs/npm. To be honest I am not sure anymore whether I installed using curl or using the download/make procedure. But in the end you should be able to install dependencies using npm. I just love the way npm is used to update modules. Not easy when using multiple projects that need different versions. But maybe there is a solution to that as well. For now, lets focus on installing some modules or dependencies. Everything needs to be done with sudo, just so you know. No worries, I’ll explain the different modules later on.

# sudo npm install express
# sudo npm install jade
# sudo npm install sass

Time to check if your environment works, try to execute the famous HelloWorld sample. But first issue the command: node –version. The following code block shows the sample as presented on the Node.js homepage.

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

Now start the server with node using : node helloworld.sh and point your browser to http://127.0.0.1:8124/.

Now you have your http server running, nice stuff.

The sample

The sample is all about providing a blog. The structure of the sample is based on the original sample. We have a public folder, a views folder and the application js files are in the root. These folders are used later on in the express code. Express is a web modules for Node.js. You can find out more about the module here: http://expressjs.com/. The next section explains a bit more about using expressjs.

The sample can be started using the app.js file by calling node app.js. We start by analyzing the app.js file.

var express = require('express');
var pub = __dirname + '/public';
var app = express.createServer();
var ArticleProvider = require('./articleprovider-memory').ArticleProvider;
var articleProvider = new ArticleProvider();
// ... more express stuff, will be discussed later on
app.listen(3000);
console.log('Express server started on port %s', app.address().port);

First we obtain the express modules, then we define a folder called pub that points to the public folder as mentioned before. In line 3 we create the express server and an ArticleProvider. The ArticleProvider is copied 1-on-1 from the article that was mentioned before. It is an in memory implementation for the datastore of the blog items. Check the sourcecode if you want to learn more about it. The final two lines are setting the port for the server to start, start the server and print a line to the console that the server has been started.

In the next section we will configure the express server.

Express

More information : http://expressjs.com/.

The following code block is the remainder of the application. There are two parts in the code block. The first part is the configuration of the server, the second part configures the url handling. Within the server configuration we define the view engine (jade) and the folder where the views can be found. Another thing is the folder where the stylesheets in sass format are that need to be compiled. We also define the folder where the public files are using the static method. The last configuration is the bodyParser. This is required for handling the post. The second part about url handling is covered after the code.

app.configure(function() {
    app.set('view engine', 'jade');
    app.set('views', __dirname + '/views');
    app.use(express.compiler({ src: pub, enable: ['sass'] }))
    app.use(express.methodOverride());
    app.use(express.static(pub));
    app.use(express.logger());
    app.use(express.bodyParser());
});

app.get('/', function(req, res) {
    articleProvider.findAll(function(error, docs) {
        res.render('blog', {locals: {docs: docs}});
    });
});

app.get('/blog/new', function (req, res) {
    res.render('blog_new', {locals: {title: 'New Blog Item'}});
});

app.post('/blog/new', function (req, res) {
    console.log('The provided title is : %s',req.body.new_title);
    articleProvider.save({title: req.body.new_title, body: req.body.new_body},
            function(error, docs) {
                res.redirect('/');
            });
});

Within the sourcecode you can identify three urls that are handled: /, /blog/new and a post to /blog/new. Notice that we use callbacks? This is what Node.js is all about, handling async callbacks. If you look at the app.get method for ‘/’ you’ll see that we call the findAll method of the ArticleProvider. The result is used to render a view with the name blog. The part with locals is used to provide parameters to the view. In this case we provide the returned docs to the view. The next section will show you the very basics of jade, a template engine.

Jade

More information can be found here: https://github.com/visionmedia/jade.

Jade is a high performance template engine heavily influenced by Haml and implemented with JavaScript for node.

I am not going to give a lot of details about jade here. The following code block shows you the view with all the blog items.

h1 My blog
div
    a(href='/blog/new') New blog item
div#articles
    - each blog in docs
        div.article
            div.title #{blog.title}
            div.created_at #{blog.created_at}
            div.body #{blog.body}

As you can see, the code is very condensed. A good tool with code completion would be nice though. Still if you have some programming experience it should not be to hard to read. Check the mechanism for making a distinction between a class and an id. # is used to represent an idea and a ‘.’ for a class. These both will be good to use in a stylesheet. Which is a nice bridge to the next section. This section is about sass that needs to be compiled in a stylesheet. The following code block shows the layout.jade file. This file contains the main template with the header of all pages. Check the way to define we use html 5.

!!! 5
html(lang="en")
  head
    title My Blog
    link(href="/style/style.css", media="screen", rel="stylesheet", type="text/css")
  body
    div!= body

Sass

More information can be found here: https://github.com/visionmedia/sass.js.

Is a condensed way of writing stylesheets. Before the stylesheets can actually be user they need to be compiled. This is done by express, check one of the earlier sections. The following codeblock shows the complete stylesheet. I guess it should not be to hard to follow if you have stylesheet experience.

body
  :font-family "Helvetica Neue", "Lucida Grande", "Arial"
  :font-size 13px
  :text-align center
  =text-stroke 1px rgba(255, 255, 255, 0.1)
  :color #555
h1, h2
  :margin 0
  :font-size 22px
  :color #343434
h1
  :text-shadow 1px 2px 2px #ddd
  :font-size 60px
#articles
  :text-align left
  :margin-left auto
  :margin-right auto
  :width 320px
  .article
    :margin 20px
    .created_at
      :display none
    .title
      :font-weight bold
      :text-decoration underline
      :background-color #eee
    .body
      :background-color #ffa

Concluding

There you have it, my first try on Node.js with extensive help of Ciaran Jessup. I do like Node.js., I love the speed of development. Would be nice to have some IDE support. I tried WebStorm, but it does not have Node.js support. It does help with the JavaScript coding. I will definitely continue playing around with Node.js. The next step is have a look at Rabbitmq.js. Finally I want to extend another sample of mine that makes use of the Axon framework with rabbitmq and Node.js for the front end. I also want to have a good look ar Socket.IO. So stay tuned for more blogs on this topic.

Resources

  • https://github.com/jettro/nodejstryout
  • http://howtonode.org/express-mongodb
  • http://nodejs.org/
  • https://github.com/isaacs/npm
  • http://expressjs.com/guide.html
  • https://github.com/visionmedia/jade
  • https://github.com/visionmedia/sass.js
Tagged on:                 

4 thoughts on “First steps with Node.js

  • April 22, 2011 at 6:15 am
    Permalink

    You forgot to include the name of the jade templates and stylesheet and where to save them

    Reply
  • March 18, 2011 at 1:32 am
    Permalink

    Once your apps are running localhost, you can deploy your node.js apps to Nodester for free! Nodester is an open source, node.js hosting platform and service. The Nodester source code is located on GitHub!

    Reply
  • March 16, 2011 at 10:53 pm
    Permalink

    Yes node.js is cool – shows that JS is not a “toy” language :)

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>