Sunday, August 4, 2013

Using Node.js and Non-Blocking Code


One of the largest strengths of Node.js is its great usage of non-blocking code.

In essence, non-blocking code creates a function to handle events as they come, so the program or application will be able to handle new events even if they arise during the last event's execution.


It's the difference between these two bits of code:

var contents = fs.readFileSync('/etc/hosts');
console.log(contents);
console.log('Doing something else');

...and...

fs.readFile('/etc/hosts', function(err, contents) {
  console.log(contents);
});
console.log('Doing something else');

But what's best, is to define a callback function...

var callback = function(err, contents) {
  console.log(contents);
}

...so it can easily be called with one line of code.

fs.readFile('/etc/hosts', callback);