O'Reilly logo

Smashing Node.js: JavaScript Everywhere, 2nd Edition by Guillermo Rauch

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3: Blocking and Non-blocking IO

Much of the discussion about Node.JS is centered around its capabilities to handle a lot of concurrency. In simple terms, Node is a framework that offers developers a powerful way to design networking applications that will perform really well in comparison to other mainstream solutions, provided that they understand the tradeoffs and what makes Node programs perform well.

With great power comes great responsibility

Node introduces a complexity to JavaScript that you’re probably not really used to managing much in the browser: shared-state concurrency. As a matter of fact, this complexity is also inexistent in traditional models for making web applications like Apache and mod_php or Nginx and FastCGI.

In less technical terms, in Node you have to be careful about how your callbacks modify the variables around them (state) that are currently in memory. Thus, you need to be especially careful about how you handle errors that can potentially alter this state in unexpected ways and potentially render the entire process unusable.

To fully understand this, imagine the following function, which gets executed every time the user makes a request to the URL /books. Imagine also that the “state” is a collection of books that you’ll ultimately use to return an HTML list of books.

var books = [

    ‘Metamorphosis’

  , ‘Crime and punishment’

];

function serveBooks () {

  // I’m going to serve some HTML to the client

  var html = ‘<b>’ + books.join(‘</b><br><b>’) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required