Nodejs Callbacks

In Node js callback is used for async programming. It is used to call at the end of each task or completion of a task. All the api in nodejs supports callback.

For example: when reading a file, it doen’t wait for the result instead control is passed to next line.

Here in nodejs, when the file I/O is done, a callback function is called with two param, err and data. So application will not go under I/O blocking. This makes nodejs process more request and faster.

Let’s utilize the demo.txt which contains hello world.

Hello World

Let’s create a file node-read.js with below code.
var nodefs = require("fs");
var data = nodefs.readFileSync('demo.txt');
console.log("Program Ended");

With this above code, application is Blocked for I/O. i.e application will read the file and print the data in it and then prints “program ended”. If the file is very large then it waits until it is read and printed. The control is passed only after I/O is released.

Below SS shows the output of this program.

Node Read JS

Non-Blocking I/O

With the help of callback function, applications no longer need to wait. There will not be any I/O blocking hence control is passed to next line and ?program end is printed even before the file is read. Once I/O is complete the callback function is executed. Below sample code shows non-blocking IO and error handling inside a callback function.

Let’s create a file “node-callback.js” with below code
var fs_module = require('fs');
 fs_module.readFile('demo.txt', function(err, data) {
        console.log(data.toString());  // content / data inside the file
console.log("Program Ended");

Below SS shows the output of this program.

node callback js

Subscribe Now