Jump to content




Recent Status Updates

View All Updates

Binpress - Cut your development time and costs in half
Photo
- - - - -

The Node.js -- Part4: Understanding Node.js Platform

node node.js javascript node basic understanding node eventloop blocking-nonblocking synchronous-asynchronous

  • Please log in to reply
No replies to this topic

#1 kernelcoder

kernelcoder

    CC Devotee

  • Expert Member
  • PipPipPipPipPipPip
  • 990 posts
  • Location:Dhaka
  • Programming Language:C, Java, C++, C#, Visual Basic .NET
  • Learning:Objective-C, PHP, Python, Delphi/Object Pascal

Posted 18 February 2013 - 01:45 AM

In this part of this series tutorial we will emphasize on the node instruction execution mechanism with some basic concepts of node platform. In this tutorial we will learn how Node.js executes codes, how we get everything asynchronous, the mechanism of asynchronous operation etc.
 
Check out our other node.js content
 
Purpose of Node.js
Node.js is made for specially scalable server application. Node.js uses javascript language structure, processes code sequentially. So some instructions may block node processes because of their processing time, availability - unavailability of the required resources. Confusing? In this sense node has introduced an excellent processing mechanism -- every IO operation will be asynchronous, thus node is growing up. We can say Node.js is the most successful event driven programming model of the web and is using to build scalable server application in an easy way and people can do  anything in this platform. 
 
 
Synchronous - Asynchronous IO Concept
Node.js is all over event driven IO platform mostly used for very fast secure network application development. Node.js executes every IO (Network, File or Inter Process Communication) operation asynchronously that means when the IO operation is running other codes are also running at the same time. After the IO operation finishes there will be two possible events -- either data or error event. So when the event occurs the corresponding callback function is executed and we are free to  do anything with the data in the callback function.
 
Node.js is made for asynchronous IO operation but we can think a case where we need the fetched data for the next few instructions to be executed otherwise the program may crash. So in that case we can make our IO operation synchronous. In fact Node has two types of IO functions for those two purposes.
 
Example:  readFile() is an asynchronous function by default but readFileSync() is synchronous version. So for each IO purpose there are two options for you to choose as your need. Each synchronous node function name is Sync ended.
Lets see some events. We have created our basic http server. There we used a function createServer() that generally takes a callback as argument and the callback function is executed when the ‘request’ named event is occurred. The request event occurs when the server gets a http request from client.
 
 
The Event Loop Concept
The Event Loop idea is: A loop that processes the event queue. Each events goes in the queue ans waits until their turn comes. The event loop pops events one by one and executes their corresponding callbacks. When all the events are popped up the event loop waits until next event is pushed in the queue. When an event is occurred the corresponding handler is executed asynchronously that means everything run in parallel process except the code. Except the code! Lets explain this with an example.
 
Node.js runs our application in single thread but when needed Node executes multiple threads for its own purpose. Thus we get
everything asynchronous. When an IO event occurs its queued  and node internally process this by multithreading mechanism and when the IO operation is done that means data is ready,  the corresponding callback is executed.
 
 
Blocking  Non-Blocking Concept
There are two things that can block the Event loop 1)Synchronous IO operation  2) Big loops. Blocking non-Blocking mechanism is explained here with an example.
 
//file testBlockingserver.js
console.log('Starting app at time: '+ new Date().toTimeString());
 
//will wait for 1 second to run the callback function
setTimeout(function() {
     console.log('setTimeout run at  ' + new Date().toTimeString() );
}, 1000);

var start = new Date();
console.log('Starting loop at: ' + start.toTimeString() );

// run a loop for 4 seconds
var i = 0;
// increment i while (current time < start time + 4000 ms), will not be interrupted once started iterating

while(new Date().getTime() < start.getTime() + 4000) {  i++;}

console.log('Exiting loop at: ' +new Date().toTimeString()  + '. Ran '+ i + ' iterations.');
 
 
After running this code we get 
node4testBlockingserver.png
 
See the setTimeout() function was waiting for 1 second at that time other codes are running but when the loop taking 4 seconds to complete to run,  the setTimeout() should run while running the while loop but Node follows Blocking mechanism in running code so the setTimeout() waits for the while loop ending and then it runs. So Node.js has a Blocking mechanism in code execution process but in IO operation node acts as a non-Blocking system. Lets see an example for Blocking system. Append this code after the testBlocking.js
 
 
//reading file by synchronous way
var fs = require('fs');
var data = fs.readFileSync('test.txt','UTF-8');
console.log("Running after the data is read from the file. Data is:\n "+data);
 
After running the code we will see
node4testBlockingserver2.png
 
See the setTimeout() is still waiting after the while loop ends and run after the readFileSync() function is finished its operation. Notice that the readFileSync() is taking two arguments filename and encoding of the output data. There is no callback function to run when the data is read rather it returns the data to a variable.
 
The test.txt file has just one line of string
 
//file test.txt
this data is in test.txt file
 
But if the file would have more than 10Mb data, then reading the file will block other codes to execute and this may cause our application purpose failure. Hence the asynchronous IO concept came into Node.js to work with most connections without interrupting  other client requests.
 
 
Recommended reading    
Event Loop Concept: http://blog.mixu.net...-js-event-loop/
Handson nodejs:  http://nodetuts.com/...odejs-book.html

Attached Files


Edited by Roger, 19 February 2013 - 02:44 PM.
added links

  • 0





Also tagged with one or more of these keywords: node, node.js, javascript, node basic, understanding node, eventloop, blocking-nonblocking, synchronous-asynchronous

Powered by binpress