What is callback in Node JS?
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 function in NodeJS.
Asynchronous behavior of NodeJS allows executing the code without waiting for the database query, any I/O operation within the function, etc. It promotes the callback behavior of NodeJS.
All the APIs in NodeJS 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 the 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.
See the following two examples, and try to figure out the main difference between them.
Example of a function without the callback back function
- Create a text file and name it practice.txt. Insert the following text in the file.
I am learning NodeJS at NodeJS Tutor.
2. Create a JS file by naming it main.js. Put the following 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 we 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.
I am learning NodeJS at NodeJS Tutor.
After verifying the above output, consider the following example that makes use of the callback function.
- Create a file with the following content and name it input.txt.
I am learning NodeJS at NodeJS Tutor.
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 I am learning NodeJS at NodeJS Tutor.
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.
Watch the above video to learn more about Callback functions in NodeJS.