Fun With Node

| Comments

Now I’m starting to have fun with Nodejs. This is because the excellent tutorials from Node tuts and because WebStorm is awesome.

Here is a first line of javascript:

hello.js
1
console.log('behold, the pizza is in the oven.');

Let’s run it with Node:

node
1
2
$ node hello.js
behold, the pizza is in the oven.

Why is this even cool? We just ran javascript without a browser, on a server.

Blocking vs non-blocking

This is an example of blocking code:

read_file.js
1
2
3
4
var fs = require('fs');
var contents = fs.readFileSync('/etc/hosts');
console.log(contents);
console.log('Now on to the next function');

This will run line by line, and all other processes are blocked until its finished.

With Node, we should be writing non blocking code, like this:

read_file.js
1
2
3
4
5
6
var fs = require('fs');
fs.readFileSync('/etc/hosts', function(error,contents) {
console.log(contents);
}

console.log('Now on to the next function');

The readFileSync accepts two parameters, the file to read and another function: the callback function. The callback function has 2 parameters, one that contains the error (if there is one) and one that contains the result.

We can also write the function like this:

read_file.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var fs = require('fs');

//a callback function returns the result, asynchronuously.
//a callback function always has 2 parameters, first is the error and the second is the result
function callback(err, results) {
    if (err) return handleError(err);
    console.log(results);
}

//in node, in third party libraries, the last parameter from a function is the callback.
fs.readFile('/etc/host', 'utf-8', callback);

//we can read a second file. This would run in parallel, it's non-blocking!
fs.readFile('/etc/vim/vimrc', 'utf-8', callback);

I think it’s more readable to add the callback function as a parameter and then we can omit ‘callback’ and use an anonymous function:

read_file.js
1
2
3
4
5
6
7
//the callback function is the last argument
//the callback function always has 2 arguments, error and results.
fs.readFile('/etc/hostst', 'utf-8', function (err, results) {
        if (err) return handleError(err);
        console.log(results);
    }
);

So this is the essence of Nodejs:

  • stop writing threads and other procedural blocking code
  • start writing asynchronous code
  • in a third party lib the last parameter is the callback
  • in a callback function the first parameter is the error, the second parameter is the result.

Comments