Node.js: Callbacks - Day Four

Node.js is an event driven asynchronous I/O based programming language. Callback is responsible for asynchronous behavior of Node.js programming language. While starting any discussion on callback function, first, we need to understand what is synchronous and asynchronous behavior of a programming language?

Synchronous (Blocking)

Blocking or Synchronous means your code can’t be run because some other process prevents it. Your process will wait for the completion of another process and your process will start to execute after the completion of the process, which is blocking your process. Let's take an example.

I have a text file, which contains some data.

text file

Now, I will try to read this file.

  1. var fs = require("fs");  
  2. var data = fs.readFileSync('E:/data.txt');  
  3. console.log(data.toString());  
  4. Callback();  
  6. function Callback() {  
  7.     console.log("***************");  
  8.     console.log("This is Callback function");  
  9. }  


This is an example of blocking (Synchronous ) process because in this process, we are reading the data from a text file. System will execute this task. First, it doesn’t matter how much time is taken by this task. After the completion of this task, the next line of code will execute. Hence, the text of “data.txt” file will read and Callback function will be called.

Asynchronous (Non-Blocking)

Asynchronous or Non-Blocking process means if any process takes long time, CPU doesn’t wait for the completion of the current process. Instead of this, CPU will start the execution of the next steps and the current process is also run in the background. Let’s take an example.

  1. var fs = require("fs");  
  2. var data = fs.readFile('E:/data.txt'function(error, data) {  
  3.     console.log(data.toString());  
  4. });  
  5. Callback();  
  7. function Callback() {  
  8.     console.log("***************");  
  9.     console.log("This is Callback function");  
  10. }  


What is a Callback ?

Callback function is a function, which is passed to another function, which will be invoked at some point, fenerally, after the completion of any task. The idea behind the callback function is an asynchronous programming implementation. Suppose, we are reading a large file and we don’t want to keep Node.js Server busy during this period. Thus, we tell it to perform this operation in the background and call a function, when it completes. This function is called a callback function.

  1. var fs = require("fs");  
  2. console.log("Fs Module implemented");  
  3. var CRS = fs.createReadStream('E:/data.txt');  
  4. console.log("Callback function for data");  
  5. CRS.on('data', writeCallback);  
  6. console.log("Callback function for Close");  
  7. CRS.on('close', closeCallback);  
  9. function writeCallback(data) {  
  10.     console.log(data.toString());  
  11. }  
  13. function closeCallback() {  
  14.     console.log("File read Successfully");  
  15. }  
  16. console.log("!!Finish");  


The code given above, shows a perfect example of Non-blocking and callback concept. In this example, we are reading a file from the system and implementing two Call back functions, namely “writeCallback” and “closeCallback” function, which will be call “data” read and “close” events.

How Node.js performs Non-Blocking and Asynchronous Tasks

Node.js contains a single thread. Afterwards, it maintains the non-blocking and asynchronous mechanism. Answer to this question is that Node.js uses the observer pattern. It means Node.js performs an event loop, using “libuv” library. Whenever any task completes, it runs the corresponding event, using the callback function.
Node.js contains Chrome’s V8 engine, which is used to run JavaScript code, which runs a single set at a time or a single line at one time.
Node.js also contains another library, which is “libuv”. This library is responsible to perform the Node.js task at the lower level at an operating system level like reading the files, connection with the database or downloaing something from the Server. “Libuv” library contains a queue of an event, which has been completed. Major part of “Libuv” is an Event Loop. It is a loop, which checks for the completion of any task and if any event completes, it invokes the event’s corresponding callback function. The image, given below, describes the whole process:
“Libuv” library performs the task at the lower level(OS level). When OS completes any task, it writes “task done” status in queue. “Libuv” checks the queue constantly, using the Event Loop. If it finds the completion of any task, it invokes the corresponding callback function. In node.js, each inbuilt module performs the asynchronous task. Each asynchronous function accepts a callback function, which will invoke on the completion of the task. I think, now it is clear, how Node.js application works?

I hope, you liked this article. If you have any doubts, write in the comment section.

Up Next
    Ebook Download
    View all
    View all