Callback Function in Node JS

C

What is callback concept in Node JS?

As we know that Node JS uses core concepts of JavaScript. The callback function is called after the completion of a specific task. During the Node JS development, a developer makes heavy use of the callback concept of Node JS.

Asynchronous behavior of Node JS allows executing the code without waiting for the database query, any I/O operation within the function, etc. It promotes the callback behavior of Node JS.

All the APIs in Node JS make use of callbacks. Consider the following example to have a clear idea of the Node JS callback function.

For instance, you create a function that performs some read and writes operations in the file. If you are using some language that does not support the callback function, you can note that the read/write operations on file will make the program wait for the operation to complete first before moving to the next line of the code.

This is the real beauty of callback function, that allows the instruction pointer IP to move to the next line of code without waiting for the read/write operation to complete. You just tell the program that whenever the operation will complete, call the callback function and make use of the results returned after that read/write operation.

The callback function in Node JS allows handling a large number of requests quickly, without waiting for any operations.

Understand the following two examples, and try to figure out the main difference between them.

Example of function without callback back function

  1. Create a text file and name it something like practice.txt. Insert the following text in the file.
NodeJsTutor is giving self learning content
to teach the world in simple and easy way!!!!!

2. Create a JS file by naming it something like main.js. Put the following piece of code in it.

var fs = require("fs");
var data = fs.readFileSync('input.txt');

console.log(data.toString());
console.log("Program Ended");

In the above code, we import “fs” to work with the files and console some messages. In the next step, run the script.

3. Run the following command to run your node program.

$ node main.js

The above code will output the following text in the console.

NodeJsTutor is giving self learning content
to teach the world in simple and easy way!!!!!

After verifying the above output, consider the following example that makes use of the callback function.

  1. Create a file with the following content and name it something like input.txt.
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

2. Now, either update the main.js file which you have created in the above example or create a new one for this example. Put the following piece of code in it.

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 the following command to run the code.

$ node main.js

It will produce the following output in the console.

Program Ended
NodeJsTutor is giving self learning content
to teach the world in simple and easy way!!!!!

Summarizing the above two examples

In the first example, we have not used the callback function of Node JS. So, the program first waits for the file content to read and log in to the console. Then it executes the next line of the program which outputs another message in the console.

In the second example, we use the callback. In the output of this example, it does not wait for the file read operation and immediately moves to the next line of the program which consoles the message Program Ended. But you must notice one thing that, the program does not stop after ending up at the last line, because the callback function returns a promise. So, it ends up fulfilling that promise.

Callback vs non Callback function

Out of callback and normal function, the choice depends on the scenario. In the case where you need to implement the simple logic and the program needs some data to process in the next lines of code, then you must keep it sequential.

But, if you want speed optimization and your function does not contain any dependency of file I/O data, database, etc, you can use the callback function.

Reference to the official callbacks in Node JS documentation

About the author

Tutor Network Team

Add comment

Tutor Network