Node.js Callback Function

Node.js Callback Function : Asynchronism is one of the fundamental factor for Node.js to have become popular. And Callback is the realization of asynchronism for functions. Generally, in Node.js, most of the functions that work on resources have callback variants.

When an asynchronous function is called upon a resource for some task, the control is let immediately to continue with the subsequent statements after the function. The task on the resource would start in parallel. This helps Node.js continue with other tasks while the function is working with the resource. Once the task with the resource is completed, Node.js resumes with the callback function. Callback function is called with arguments : data object, result object and (or) error object containing information regarding the task.

Blocking Function : In contrast to asynchronous function, a synchronous function blocks the execution until the task on the resource is completed. Therefore synchronous function is also called as blocking function.

Node.js Nested Callback Function : If there are multiple operations to be done on the resource sequentially, and also has to be done asynchronously, you may nest the callback functions, one in another.

Now we shall see the working of a callback function in comparison with a blocking function, on reading (task) a file (resource).

  • Example for Node.js Blocking Function
  • Example for Node.js Callback Function
  • Example for Node.js Nested Callback Function


Example for Blocking Function

Following is an example node script which reads a sample.txt file synchronously.

When the above program is run

TheAfter readFileSync statement  is always executed only after reading the file is completed.fs.readFileSync  is blocking the execution flow.

Example for Node.js Callback Function

Following is an example node script which reads a sample.txt file asynchronously, with the help of Node.js Callback Function.

When the above program is run

You may observe that even after executing console.log("After readFile asynchronously statement, it took around 5ms to complete reading the file. fs.readFile('sample.txt', callback function{..}) 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 resource).


Example for Node.js Nested Callback Function

To demonstrate Node.js Nested Callback Function, we shall consider a scenario of renaming a file and then deleting it using asynchronous functions.

When the above Node.js example is run with node


Conclusion :

In this Node.js Tutorial – Node.js Callback Function, we have learnt the execution flow of Callback functions and how they are non-blocking, and also how to use nested callback functions with examples.