Node.js Non-Blocking I/O Model

Siddharth
2 min readJun 12, 2021

According to nodejs.org,- “Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.”

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, fs.readFile() is non-blocking so JavaScript execution can continue and 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.

--

--