Wednesday, April 8, 2020

Node Architecture

Node Architecture

Node.js is based upon an event-driven, light-weight, and non-blocking I/O model. This is a lightweight, minimal framework based on the Google Chrome V8 engine. The Event-loops are the soul of event-driven programming, almost all the programs using UI use event-loops to detect and react to the user events.
Like Clicking a button, Ajax Requests, etc.

Node.js is a command-line tool(See getting started with Node). It is a high-performance network application, JavaScript minimal framework well suitable for the concurrent environments. Node is not just JavaScript, its major part is written in C/C++.

Node.js Architecture

Node uses event-loops by JavaScript callbacks to implement the non-blocking I/O. (We must always keep in mind that JavaScript used in Node is not exactly same as we know, it is different, in fact, it is no DOM implementation used by Node, so be careful).

Everything inside the Node runs upon a single thread(main thread), and this thread should never be blocked. It means if we need to wait for something to happen, it must provide a callback. So CPU-intensive operation must be kept off from the event-loops.


Conventional IO Model

var myresults=db.query("Execute some query in database");   
      //wait forre results to load             
      //execution will be blocked untill the
      //executeWith(myresults) finishies              

Non-blocking IO Model

db.query("Execute some query in database",function(myresults){           
      executeWithResults(myresults);//wait for result     
 executeWithOutResults(); //executes without any delay!                  

Blocking Vs Non-blocking IO

The conventional model is an asynchronous model. It waits for input before proceeding. The thread is blocked.

Non-blocking IO is asynchronous, the main thread is not blocked and keeps executing without blocking. The Node.js implements a non-blocking IO with event-based JavaScript callbacks.

The biggest advantage of non-blocking IO is no-overhead is associated with the threads, so we can handle lots of client requests at the same time. This is best for achieving the high-concurrency.

Threads consume resources like memory on stack and some processing time is consumed in order to provide context switching among the threads.

On the other hand, no thread management is required in non-blocking IO. Only JavaScript callbacks are executed when some event occurs.

These callbacks are usually in the form of anonamous functions.