Node.js Callback Concept

Understanding the Concept of Callback

Callback is an asynchronous equivalent for a function that is called at the completion of a task. The Callback helps to avoid any I/O blocking and allows other code to execute in the period in-between. Node.js provides an Asynchronous platform that doesn’t wait for finishing the file I/O, which implies that Node.js uses Callbacks, making the Node.js platform highly scalable.

Blocking vs Non-Blocking

The operations that block any further execution until the current operation completes, are referred as Blocking. However, the operations that don’t block any execution are referred as Non-Blocking. As per the Docs of Node.js, the Blocking in Node.js happens when the execution of an additional JavaScript process waits until a Non-JavaScript process ends, which implies that Blocking methods works Synchronously; whereas Non-Blocking uses Asynchronous method with the help of Callback function.

Let’s see some examples given below that are based on the fundamental concept of Callback.

Blocking Example

File: blocking.js  

// Blocking
// Importing the fs module
const fs = require('fs');
console.log("This is an Example of Blocking");
// Reading the content of a file
var text = fs.readFileSync('./mytext.txt');
console.log("Content of the File: " + text.toString());
console.log("Program Ended!!");

To execute the above program, type the following command on the terminal:

$ node blocking.js

The Output is as follows:

This is an Example of Blocking
Content of the File: Hello! Welcome to tutorialandexample.com
Learning is so easy with tutorialandexample.com
Program Ended!!

Non-Blocking Example

File: non-blocking.js

// Non-Blocking
// Importing the fs module
const fs = require('fs');
console.log("This is an Example of Non-Blocking");
// Reading the content of a file
fs.readFile('./mytext.txt', function ( err, text ){
    if ( err ){
        return console.error(err);
    }
    console.log("Content of the File: " + text.toString());
});
console.log("Program Ended!!");

To execute the above program, type the following command on the terminal:

$ node non-blocking.js

The Output should is given as follows:

This is an Example of Non-Blocking
Program Ended!!
Content of the File: Hello! Welcome to tutorialandexample.com
Learning is so easy with tutorialandexample.com

From the above script files and their outputs, we can conclude that the execution of code in the Blocking program is done in order. However, the execution of code in the Non-Blocking program is not done in a sequence. The execution of other codes doesn’t wait for the completion of the code to being executed.