Sunday, February 17, 2013

Event driven, asynchronous callbacks and Node.js

Node's approach of code execution isn't unique, but back end execution model is different from environments like PHP or Java.

Node.js core provides methods to reading content of a file in the file-system. fs module provides variety of file system methods.The easiest way to read the entire contents of a file is as follows.
fs = require('fs');
fs.readFile('/home/udara/docs/users.txt');
console.log("Hello Users !!");
Let's assume that the time taken to read users.txt is really long, JavaScript interpreter of Node.js first has to complete reading the users.txt file, and then only it execute the console.log() function. Same as in PHP if this code would be part of a webpage, the user have to wait until it read whole file at once and load the page.

Unlike PHP, Node.js there is only one single process. If there is something happen like above example this will effect the whole process and each and every user would be affected. But in PHP only user who request that web page feel slow page load, but other users requesting other pages would not be affected. 

So where is asynchronous of Node.js ????

fs = require('fs');
fs.readFile('/home/udara/docs/users.txt', function (error,data) {
console.log(data);
});
console.log("Hello Users !!");
Here, without expecting fs.readFile() to directly return a file content to us we pass second parameter an anonymous function.Now Node.js can handle fileread request asynchronously.Only when fileread is done then it will execute anonymous function that was passed to fs.readFile().

Without waiting for the fileread output system will out put Hello Users !! to the console.

 

No comments:

Post a Comment