Home >>Nodejs Tutorial >Node.js Callbacks Concept

Node.js Callbacks Concept

Node.js - Callbacks Concept

Callback to a function is an asynchronous analog. Upon completion of a given task a callback function is Called. Node leverages strong callbacks. All the Node APIs are written in such a way as to support callbacks.

For example, a file-reading function can start reading file and immediately return control to the execution environment so that the next instruction can be executed. If the I / O file is complete, the callback function will be called while passing the callback function, the file content as a parameter. So there is no blocking or waiting for the I / O file. This makes Node.js extremely scalable, as it can process a large number of requests without waiting for any feature to return results.

Blocking Code Example

Creates a text file called input.txt with the content–

Phptpoint providing self-teaching learning 
Content In a simple and easy way

Build a js file with the following code called main.js –


var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
	

Run main.js now to see the result –

$ node main.js
Verify the Output
Phptpoint providing self-teaching learning
Content In a simple and easy way
Program Ended

Non-Blocking Code Example

Creates a text file called input.txt with the content below.

Phptpoint providing self-teaching learning 
Content In a simple and easy way

Main.js update to get the following code –


var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");

Run main.js now to see the result –

$ node main.js
Verify the Output
Program Ended
Phptpoint providing self-teaching learning
Content In a simple and easy way

Those two examples illustrate the blocking and non-blocking calls concepts.

    1. The first example demonstrates that the program blocks until the file is read, and only then proceeds the program ends.
    2. The second example demonstrates that the program does not wait for file reading and will print "Program Finished," while the program proceeds to read the file without blocking.

      Thus a sequential blocking program executes a lot. It is easier to implement the logic from the programming point of view but non-blocking programs do not execute in sequence. In case a program needs to use any data to be processed, to make it sequential execution should be held within the same block.


No Sidebar ads