Non-blocking implementation with node.js for scalable application

In a normal program normally instructions are executed one by one. Later instructions has to wait till earlier instructions are finished. For this problem we can use threads with some programming languages like java.

following code snippet shows how to code in non-blocking mode to read a file. and you will notice code after reading file will execute while node.Js reading the file. ("task finished" will be printed first)

var fs = require("fs");

fs.readFile('file.txt', function (err, data) {
    if (err) return console.error(err);
    console.log(data.toString());
});

console.log("Task Finished");




Here is the same code in blocking-mode and you will notice "Task Finished" will be printed at the end.

var fs = require("fs");

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

console.log(data.toString());
console.log("Program Ended");


No comments:

Post a Comment