Nodejs callback function and its concept in 2024

By Haribabu | Last Updated on July 21, 2024

Nodejs has become widely popular due to its core factor, “Asynchronism”. A callback is an asynchronous functional paradigm that often refers to be as a “Higher-order function.” In Nodejs, most of the functions work as callback variants. Only the function definition is passed when an argument(callback function) in Nodejs is passed to another function. This calling function mechanism is solely responsible for the timing of callback function execution. This is the sole basis of the asynchronous behavior of the Nodejs framework. 
Create a safe and secure eCommerce solution with White Label - Headless CMS!!!
A callback function is a function which is:
  • Accessible by another function, and
  • It starts after the first function gets complete.
These functions in JavaScript will always pass as arguments to other functions. A callback function is called with arguments containing information that relates to the tasks:
  • data object
  • result object, and 
  • error object 
Node uses callback functions heavily so all the APIs of Nodejs are created in such a way to support callbacks.  For example, If a file I/O is complete, it will call the callback function while passing the callback function. And the remaining content of the file as a parameter. So there is no wait for File I/O. Such an execution property called non-blocking makes Nodejs highly scalable. Thus, enabling it to process a high number of requests without waiting for any function to return results.

Blocking function

Unlike the asynchronous function, the synchronous function blocks all the executions that require to complete a specific task. In simple, blocking function blocks the execution until the task on the resource is completed. So, that was the reason why the synchronous function refers to be a blocking function.
Read More: How To Install Node Version Manager NVM?

Nodejs callback function 

Nodejs and JavaScript callback function Nodejs nested callback function is a JavaScript function where it can be nested within other functions. A nested function or inner function can access the arguments and variables of an outer function where it is nested within. You can nest the callback function if any need for multiple operations to be done asynchronously.

Examples for Nodejs functions

With a few sample codes, we shall see how the callback function works in comparison with a blocking function, on reading (task) a file (resource) using the following examples:
  • Blocking Function
  • Callback Function
  • Nested Callback Function

Example of blocking function

Following is an example node script that reads a sample.txt file synchronously, with the help of blocking function.
read-file-sync.js

var fs = require('fs');

 // read file sample.txt

Var data = fs.readFilesync(‘sample.txt’)

console.log("Reading file completed : " + new Date().toISOString());

 console.log("After readFileSync statement : " + new Date().toISOString());
When the above program runs, the terminal output will be as follows:

Terminal output

hari@hari - VPHAS26A:~/ nodejs$ node read-file-async.js

Reading file completed : 2020-02-03t1.13:52.103z

After readFilesync statement : 2020-02-03t1.13:52.105z
In the above example, fs.readFileSync  is blocking the execution flow. The After readFileSync statement is executed only after reading the file is completed.

Example of Nodejs callback function

A node script which reads a sample.txt file, with the help of Nodejs callback function, asynchronously as shown below:
read-file-sync.js

var fs = require('fs');

 // read file sample.txt

fs.readFile (‘sample.txt’,

// callback function that is called when the reading file is done

 function(err, data) {

 if (err) throw err;

        // data is a buffer containing file content

        console.log("Reading file completed : " + new Date().toISOString());

});

 console.log("After readFile asynchronously : " + new Date().toISOString());
When the above program runs, the terminal output will be as follows:

Terminal output

hari@hari - VPHAS26A:~/ nodejs$ node read-file-async.js

after readFile  asynchronously : 2020-02-03t1.13:52.987z

reading file completed : 2020-02-03t1.13:52.992z
You may observe that even after executing console.log, it has not blocked the execution. Instead, a new process is started in parallel with the main control flow, to read the file (perform the task on the resource).

Example of Nodejs nested callback function

We can understand the Nodejs nested callback function with below sample coding. For example, we shall consider renaming a file and then deleting it using asynchronous functions.
nodejs-nested-callback.js

var fs = require('fs');

 fs.rename('sample.txt', 'sample_old.txt',

    // 1st call back function

    function (err) {

        if (err) throw err;

        console.log('File Renamed.');

        fs.unlink('sample_old.txt',

            // 2nd call back function

            function (err) {

                if (err) throw err;

                console.log('File Deleted.');

            }

        ); 

    }

);
When the above program runs with the node, the output will be as follows:

Terminal output

hari@hari-VPHAS26A:~/nodejs$ node nodejs-nested-callback.js

File Renamed.

File Deleted.
In this blog, we have learned the basics of Nodejs callback functions by covering the following topics,
  • Execution flow of Callback functions with example.
  • How they are non-blocking with example.
  • How to use nested callback functions with example.

Conclusion

Thanks for coming all this way to read about the Nodejs callback function and its concept. I hope you have gained the overall callback function concept in Nodejs. If you still have any queries regarding the Headless eCommerce with Nodejs ideas, please feel free to Contact us for zero-cost consultation today.

Leave a Reply

Your email address will not be published. Required fields are marked *