Sunday, 23 April 2017

javascript synchronous asynchronous query

I am new to Javascript.

Below nodejs code runs synchronously, I do not undestand, why?

var http = require("http");
var fs = require("fs");

http.createServer(function (request, response) {

   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

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

console.log(data.toString());   

console.log("Program Ended");

I got output as:

Server running at http://127.0.0.1:8081/
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Program Ended

Below nodejs code runs asynchronously, I do not understand, why? I agree there is a callback in the readFile function, so why it behaves asynchronously?

var http = require("http");
var fs = require("fs");

http.createServer(function (request, response) {

   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

fs.readFile('input.txt', function(err, data){
    console.log(data.toString());   
}); 

console.log("Program Ended");

Here is the output:

Server running at http://127.0.0.1:8081/
Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

Could you please someone explain me clearly why above is behaving like that.



via John

No comments:

Post a Comment