In this tutorial, we are going to see callbacks in Node.JS. As we already know that Node.Js runs on single threaded VM.  But it can handle multiple requests at the same time. Let’s understand what exactly callbacks are in Node.Js

What are Callbacks?

Node.JS itself is based on Single Threaded VM. Because of its asynchronous nature, it doesn’t wait around the task to complete. Node.Js uses callbacks to wait for the task to complete. A callback is a function that called at the completion of the given task. All the APIs in Node.Js are written in such a way that they support callback function.

If a function is performing a long-running task such as reading a file, it returns the program flow to execution environment without waiting for a task to complete to handle next request. Once the file I/O completed it will immediately call the callback function. This makes Node.Js highly scalable as it can handle the high number of the requests without waiting for any function to complete.

Blocking Code Example:

Create a text file with the name NodeContent.txt and write the following text.

Debug On Web consists of an invaluable series of programming blogs and tutorials for software developers, programmers and coders.

Create a file Blocking.js at the same location and write the following code.

var fs = require("fs");

fs.readFile('NodeContent.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");

Now open the Node.Js command prompt and run the application using the following command.

node Blocking

You will find the following result in command prompt.

Callbacks

You can see in the above output window program blocks until it reads the file. After reading the file it proceeds to end the program.

Blocking Code Example:

Create another js file called Blocking.js and write the following code.

var fs = require("fs");

fs.readFile('NodeContent.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");

On Node.js command prompt run the following command.

node Blocking

See the output window.

Callbacks

In this example, the program does not wait for file reading to complete and proceeds to print “Program Ended”. At the same time, the program continues file reading and print the file content.

View More:

Conclusion:

Hope you understand Callbacks in Node.Js. I would appreciate your feedback, Comments and Suggestion.

Thank You.

Leave a Comment