Node.js Non-Blocking I/O Model
Today, We will try to figure out what non-blocking I/O model.
“I/O” refers primarily to interaction with the system’s disk and network supported by libuv.
What is non-blocking I/O?
Any process which doesn’t block execution of the next line of code. called non-blocking I/O.
let's take an example — Treat event-cycle as a waiter at a restaurant.
Suppose, You went to a restaurant and you give an order to the waiter, he doesn’t have to wait till the food is ready to take the next order. It’s not advisable to have a separate waiter at every table.
In this case,
The single waiter took multiple orders and give them to the kitchen and once the food cooked.
he starts serving cooked food first irrespective of the order number.
One person might order a special food that could take forever to cook, and another one might just order a soup or something light that would take a minute or two. So, the latter should not be blocked by the first.
The event cycle is like a waiter, whenever a request is made, the Node takes that and registers a callback function (like saying the food is being cooked, go and take other orders). Now, the event cycle is free and ready to take the next request and the end-user feels a smooth transition between requests.
let's take short coding example -
In the above example,
moreWork() will be called first. The ability to run
moreWork() without waiting for the file read to complete is a key design choice that allows for higher throughput.
I hope this brief explanation helps.