Nodejs callback
A callback is a function that can be called on the completion of a given task to prevent blocking. As a result of it other code will run without waiting for a task to complete. This feature makes node.js highly scalable as it can process large numbers of requests without waiting for any function to return result.
Uses of callback methods:
Below are examples of blocking and non-blocking codes:
1. Create a text file with name test1.txt with the following content:
“Here we are explaining the node.js callbacks.”
2. Create a javascript file with name test2.js having the following code:
var fs = require("fs"); fs.readFile(‘test1.txt', function (err, data) { if (err) return console.error(err); console.log(data.toString()); }); console.log("Program Ended");
3. Now open the command prompt and execute the following command:
node test2.js
Blocking code output:
Non-Blocking code output:
As you can see in case of non-blocking code program does not wait for file reading but it just proceeded to print “Program Ended” and same time program without blocking continues reading the file.
Note: Using so many callbacks at once has a drawback known as callback hell