How Node.js Works

April 06, 2018

Non-blocking  Or Asynchronous Nature Of Node


What is Asynchronous?


For a example,Imagine you go to a restaurant.There are two tables , one kitchen and one waiter.
Waiter comes to a table and takes the order and gives it to the kitchen.Then the same waiter moves into second table while chef is preparing meal for 1st table.So the same person can serve many tables.They don't have to wait for the chef cook one meal before they serve another table.This is what we called non-blocking architecture.This is how node applications work.

The waiter is like thread allocated to handle a request.So single thread is used to handle multiple requests.
In contrast to non-blocking or asynchronous architecture we have blocking or synchronous architecture.

What is Synchronous?


Back to our restaurant example.Imagine you go to another restaurant and in this restaurant a waiter is allocated to you.He takes the order and give it to the kitchen.Now he is sitting in the kitchen waiting for the chef preparing your meal.At this time he is not going anything else,just waiting.Not going to take order from another table until your meal is ready.This is what we called blocking architecture.


How This Is Going To Apply For Node


In node we have single thread  to handle all the requests.when a request arrives,that single thread used  to handle that request.If we need to query a database our thread does't have to wait for the database to return the data.while database is executing our query that thread will use to serve another client.when the database prepares the result,it puts a message what we called event queue.Node is continuously monitoring this  queue in the background.When it finds an event in this queue it will take it out and process it.This kind of architecture makes node idle for building applications that include a lot of disks and network access.we can serve more clients without the need throwing more hardware.That is why node applications are highly scalable.

In contrast node should not be used for CPU-intensive applications like video encoding or image manipulating services.In this kind of applications have lot calculations that should be done by CPU,and the few operations that touch the file system or the network.

You Might Also Like

1 comments

Search Here