Avoid Synchronous Code in Your Application

As you know, Node.js is built around events. The whole process is a big event machine juggling different flows. Since our main process is single threaded, any function that takes a while to execute should be done in an evented manner to avoid locking up the entire application.

If you’re used to working in other programming languages, this is a tricky concept to get accustomed with. Let’s look at an example, where we implement a recursive Fibonacci calculation and a server to allow access to it:

 'use strict'​;
 
 var​ express = require(​'express'​);
 var​ app = express();
 
 // Calculating fibonacci number recursively
 function​ fibonacci(n) {
 if​(n < 3) {
 return

Get Secure Your Node.js Web Application now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.