Tuesday 2 October 2018

Node.js: Callback example

Node.js achieve non-blocking using callbacks. A callback is a function, that will be called at the completion of a task. All the APIS support callback function.

Reading a file in synchronized way
If your application is reading a file in synchronized way, then the next statements will not get executed until complete file is read.

For example,
input.txt
What is Chrome's V8 JavaScript engine?
Node.js is  JavaScript run time built on top of Chrome's V8 JavaScript engine. V8 is Google’s open source high-performance JavaScript engine, written in C++ and used in Google Chrome, and in Node.js.

HelloWorld.js
var fileSystem = require("fs");
var inputFile = 'input.txt';

var data = fileSystem.readFileSync(inputFile);

console.log(data.toString());

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


When you ran HelloWorld.js, you can see below messages in console.
C:\Users\Krishna\Documents\nodejs\examples>node HelloWorld.js
What is Chrome's V8 JavaScript engine?
Node.js is  JavaScript run time built on top of Chrome's V8 JavaScript engine. V8 is Google’s open source high-performance JavaScript engine, written in C++ and used in Google Chrome, and in Node.js.

************Program Ended***************

We can rewrite the above application using callback mechanism like below.


HelloWorld.js
var fileSystem = require("fs");
var inputFile = 'input.txt';

fileSystem.readFile(inputFile, function(error, data) {
 if (error)
  return console.error(error);
 console.log(data.toString());
});

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

Since I am passing a callback function to readFile method of filesystem, it will be called once the data is read from the inputFile. The processing is not blocked here.


When you ran HelloWorld.js file, you can see below messages in console.
C:\Users\Krishna\Documents\nodejs\examples>node HelloWorld.js
************Program Ended***************
What is Chrome's V8 JavaScript engine?
Node.js is  JavaScript run time built on top of Chrome's V8 JavaScript engine. V8 is Google’s open source high-performance JavaScript engine, written in C++ and used in Google Chrome, and in Node.js.

As you see the output, program doesn’t wait for file reading. It proceeds for further execution.



Previous                                                 Next                                                 Home

No comments:

Post a Comment