HI WELCOME TO SIRIS

Node.js Callbacks

Leave a Comment
Callback is an asynchronous equivalent for a function. It is called at the completion of each task. In Node.js, callbacks are generally used. All APIs of Node are written in a way to supports callbacks. For example: when a function start reading file, it returns the control to execution environment immediately so that the next instruction can be executed.
In Node.js, once file I/O is complete, it will call the callback function. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process high number of request without waiting for any function to return result.

Blocking Code Example

Follow these steps:
  1. Create a text file named input.txt having the following content:
    1. kansiris is an online platform providing self learning tutorials on   
    2. different technologies, in a very simple language.    
  2. Create a JavaScript file named main.js having the following code:
    1. var fs = require("fs");  
    2. var data = fs.readFileSync('input.txt');  
    3. console.log(data.toString());  
    4. console.log("Program Ended");   
  3. Open the Node.js command prompt and execute the following code.
    1. node main.js   
Node.js callbacks 1

Non Blocking Code Example

Follow these steps:
  1. Create a text file named input.txt having the following content:
    1. kansiris is an online platform providing self learning tutorials on   
    2. different technologies, in a very simple language.     
  2. Create a JavaScript file named main.js having the following code:
    1. var fs = require("fs");  
    2.   
    3. fs.readFile('input.txt', function (err, data) {  
    4.     if (err) return console.error(err);  
    5.     console.log(data.toString());  
    6. });  
    7. console.log("Program Ended");  
  3. Open the Node.js command prompt and execute the following code.
    1. node main.js   
Node.js callbacks 2

You can see that above two examples explain the concept of blocking and non-blocking calls. The first example shows that program blocks until it reads the file and then only it proceeds to end the program on the other hand in second example, 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.

So we can say that, a blocking program executes very much in sequence. It is also easier to implement the logic from programming point of view in block programs. But non-blocking programs does not execute in sequence, so in case a program needs to use any data to be processed, it should be kept with-in the same block to make it sequential execution.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.