Node js Callback Method

A callback function is used in asynchronous API. The callback function is called at the completion of some task. In Synchronous, the API is blocked or wait for process completion or return a result.

So in node.js, we are using Asynchronous callback function so that process never waits to return a result, once I/O is completed, it will call the callback function.

For example - create a text file, write the text that you want to print and save as 'input.txt'.

Blocking Process

var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Read file successfully");
console.log("Process Complete!");

Output of the above code

nodejs blocking process

Non-Blocking Process

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {
   if (err) return console.error(err);
   console.log(data.toString());
   console.log("Read file successfully");
});

console.log("Process Complete!");

Output of the above code

nodejs non blocking process

In the above two examples, you have seen the first example shows that the program blocks until it reads the file and then only it proceeds to end the program and in the second example the program does not wait for file reading and proceeds to print 'Process Complete!' and then at the same time it reads the text file without blocking.



Read more articles


General Knowledge



Learn Popular Language