Quick Contact


    Callback Concept in Node JS

    Node js performing asynchronous programming and callback function is one of the ways to help.

    -it is an asynchronous equivalent means whenever task is done, this function will be called automatically.

    – It supports or helps in Non-Blocking code means single thread don’t have to wait for some task to be completed as soon as task is done, it will call it back to perform a particular action and it also helps in maintaining the performance of single threaded as it’s asynchronous and will definitely help it to maintain the performance.

    So, let’s take the example where callback is not implemented to blocking code so see what happens.
    	Varfs = require (“fs”);
    	Console.log (“program Started”);
    	Var data = fs.readFileSync (‘input.txt’);
           Console.log (data.toString());
           Console.log (“Program Ended”);
    	

    So in this code, here code reading a file called input.txt and above “fs” module is included. So this code is synchronous programming. So first program started will print then read operation will be done then print the data and then program ended.

    But let’s consider a scenario for reading file you will take some time. Do the same thing in asynchronous programming using the callback-:
    Non-Blocking code with callback
    	Varfs = require (“fs”);
    	Console.log (“program Started”);
    	Fs.readfile(‘input.txt’, function (err, data) {
    	If (err)
    	Return console.error(err);
    	Console.log (data.toString());
    	});
    	Console.log (“program Ended”);
    	

    So here Program started and then started reading file, this is asynchronous so meanwhile this particular file is being read, then proceed to the next operation and then print and program ended. As soon as read file operation is done the callback function will call it back and then these executions will be done.

    So let’s apply this on program by taking one example of application file-:

    So in program you are going to see advantage of callback function.

    But first try something without callback in this program, so here file is reading synchronously so callback concept is not used here. In the following program internal module is used called FS which is filestream and using for redaing a file is data.txt which is actually located in the very same path as of my app.js file, a sample file taken as example.

    	“readFileSync” means you are reading file synchronously-:
    	Varfs = require (“fs”);
    	Console.log (“program Started”);
    	Var data = fs.readFileSync (“data.txt”);
    	Console.log (data.toString());
    	Console.log (“Program ended”);
    	
    So let’s see how output will look like-:
    Callback Concept in Node JS

    So here Program started and the content of the file and then finally its program ended. But if you will do same thing asynchronously.

    So here what is happening is firstly message is printed and then proceeding with the execution, So there will be large file of data then it contains large MB and it takes more time and will stop the all process just because of reading that particular file so this is how synchronized programming actually works.

    But if you replace this code with asynchronous programming then behaviour is going to be changed as-:

    	Varfs = require (“fs”);
    	Console.log (“program Started”);
    	Fs.readfile (“data.txt”, function (err,data) {
    	If (err) return console.error (err);
    	Console.log (data.toString);
    	});
    	Console.log (“Program Ended”);
    	

    So here it will print this message program started and then will start reading the read file with the method called read file the same file data.txt. But here sync method is not used here so by default it will be asynchronised and here callback function is also passed. So, what the callback function will do is as soon as this read file start doing its task and will proceed to the other things like program ended at the end of this message but as soon as this read file will be done with reading the data, it will get a callback. In case if there is any error, the will print that error and in case getting the data will print that data. But for reading that particular file will not stop the process.

    Output is as-:

    div class=”img”>
    Callback Concept in Node JS

    So here Program Started and Program Ended and then after that data of the file is visible. So, this is how the callback function enhances the performance of any program and it will not wait for any particular task to be completed and it will do things asynchronously.

    Now let’s have a look what is callback hell. Whenever you keep on nesting the callback functions to some number deep level, it will create the pyramid of doom that looks like-:

    	Varfs = require (“fs”);
    	Var file = “input.txt”;
    	Fs.exists (file, function (exists) {
    	If (exists) {
    	Fs.stat (file, function (err.stats){
    	If (err) {
    	Throw err;
    	}
    	If (stats.isfile()) {
    	Fs.readfile (file, “utf8”, function (err, data) {
    	If (err) {
    	Throw err;
    	}
    	Console.log (data);
    	});
    	}
    	});
    	}
    	});
    	

    As it is very uneasy code to read and if some programmer has done this and after ne programmer is joining in his place, it will be very confusing to understand. If there is a real time server application where you need to perform so many functionalities back to back then it will be even some more level deep and more confusing. So to remove callback hell problem what you can do, as you above there is first function, second function and there is third function which are doing in the callback rather defining the function in above respective way, you can define these functions properly and rather than defining-:

    You can make a function call which will look something like this
    	Varfs require (“fs”);
    	Var file = “input.txt”;
    	Function ReadFile (err,data) {
    	If (err) {
    	Throw err;
    	}
    	Console.log (data);
    	}
    	Function Stat (err,stats) {
    	If (err) {
    	Throw err;
    	}
    	If (stats.isFile()) {
    	s.readFile (file, “utf8”, Re)
    	} function cbExists(exists) {
    	If (exists) {
    	Fs.stat(file, stat);
    	}
    	}
    	Fs.exists(file, cbExists);
    	

    so what you see its function one function to function three and whenever you require you are calling these functions rather than defining them. So this is much clearer code in these same callback applications.

    Copyright 1999- Ducat Creative, All rights reserved.