Node.js introduction

Node.js Is a platform that can be used to build scalable network application using javascript on server-side.

Google chrome runs on a run time environment called V8 JavaScript Runtime which is written in C. Node.js is build as a wrapper to V8. Node.js  is not a Web Framework. It is a low level platform which is related to Network communication. And the most noticeable fact is that it is "Single Threaded". And it is FAST...!!!!  Surprised ?????

You might be thinking how can this be fast when it is single threaded. We will explaining this further down in  this post.

Blocking Code Vs. Non-Blocking Code

Blocking Code : 
"Read file from Filesystem, set equal to "contents".
Print contents
Do something else"
--------------------------------------------------------------------------------------------------------------------------
System waits till the reading and printing is finished to "Do something else". That means the system is blocked while the reading and printing is being done.

Example : 
 function doThatThing(){  
      var i = 10;  
      while(i>0){  
           console.log("blocking -> "+i);            
           i--;  
      }  
      console.log("Do something else.");  
 }  
 doThatThing();  

console.log("Do something else."); line will execute after the while loop is finished.
Non-Blocking Code :
"Read file from Filesystem
    whenever you're complete, Print the contents
Do something else"
--------------------------------------------------------------------
System doesn't wait till the reading and printing is finished. It does something else without waiting. Whenever the reading is finished it'll print the content.

Example:
 function doThisThing() {  
      setTimeout(function () { console.log('non blocking'); }, 3000);  
      console.log("Do something else.");  
 }  
 doThisThing()  


console.log('non blocking'); will execute after about 3 seconds executing the console.log("Do something else."); line.

First Node.js program

hello.js
 var http = require('http');          //How to require modules  
 http.createServer(function(request,response){  
   response.writeHead(200);          //Status code in header  
   response.write('Hello tech world');    //Response body  
   response.end();              //Close the connection  
 }).listen('8000');               //Listen for connection on this port  
 console.log('Listening on port 8080.....');  

How to run the code :
 $ node hello.js  
Output :
 $ Listening on port 8080.....  

If we use following command to call to the server that is running on port 8080,
 $ curl http://localhost:8000/  

The output is,
 Hello tech world  


How is this code being executed....
       
              When we execute this code, node will register the "Events". In this case there is "request event" in line 2 and it will be registered as an event. Once the execution of the script is completed, node goes into a "Event Loop". It will continuously check for events. As soon as a request come in and trigger the request event,it will run the call back function and a output will be generated as "Hello tech world".



It would be easy to understand the event loop, if we take a look at another example.

  var http = require('http');     //How to require modules   
  http.createServer(function(request,response){   
   response.writeHead(200);     //Status code in header   
   response.write('Hello tech world start');  //Response body   
   settimeout(function(){ //represent long running process  
    response.write('Hello tech world end');  
    response.end(); //Close the connection  
   },5000);   //wait 5 seconds        
  }).listen('8000');        //Listen for connection on this port   
  console.log('Listening on port 8080.....');   

There are two events in this code. request and a timeout. When each time a request arrives, the server creates a timeout event which will give a response in 5 seconds.



What would the behavior if this server gets two request at the same time ? Below diagram will explain that.


Two requests can happen at the same time and nothing will be blocked.
what if  setTimeout is blocking everything.


Everything is blocked till the setTimeout is finished executing.

Most interesting thing about node.js is that it is Non-blocking.And that enables it to create server-side network applications which are scalable and fast.

References:

Philip Roberts: What the heck is the event loop anyway? | JSConf EU 2014 :https://www.youtube.com/watch?v=GJmFG4ffJZU

Learn Node.js (Level 1) : https://www.youtube.com/watch?v=8aGhZQkoFbQ


SHARE

Harsha Jayamanna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment