Sunday, 26 November 2017

Node.js | Callbacks

Callback is an asynchronous equivalent for a function. A callback function is executed after the current effect is 100% finished. As Node.js is asynchronous so callbacks are generally used. All APIs of Node are written in a way to supports callbacks.

In the file I/O, when a function starts reading the 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 a high number of the request without waiting for any function to return the result.

callback.txt
Node.js call back example!!

Reading the file...
Finished!

NoCallback.js
This is a simple Node.js example to read a file without any callback.
var fs = require("fs");

var data = fs.readFileSync('callback.txt'); 

console.log(data.toString()); 

console.log("Program Ended");  

Output
D:\node\Callbacks>node NoCallback.js
Node.js call back example!!

Reading the file...

Finished!

Program Ended

Callback.js
This is simple Node.js callback example to read a file with callbacks.
var fs = require("fs"); 
 
fs.readFile('callback.txt', function (err, data) { 
    if (err) {
    return console.error(err); 
    }
    console.log(data.toString()); 
});

console.log("Program Ended!!");

Output
D:\node\Callbacks>node Callback.js
Program Ended!!
Node.js call back example!!

Reading the file...

Finished !

As we can see the above examples explain the concept of blocking and non-blocking calls. In the first example, program blocks until it read the file and then only it proceeds to end the program. However, in the second example, the 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.


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...