What is I/O operations?

I/O stands for input/output. I/O is used to label a communication between a process in a CPU computer and anything external to that CPU(Memory, disk, network, or even another process) and the process communicates with these external things through signals. They are input when they are received by the process and they are output when they are sent by the process.

In Node.Js’s operations term, I/O refers to network and disk operations which are the most time-consuming operations. Node’s Event Loop is designed around the fact that the largest waste in computer programming comes from waiting for such I/O operations.

Handling slow I/O operations

  • Synchronous: Easiest way to handle slow I/O by executing operations one by one. This is the worth way we can handle I/O since when we are executing one I/O operation we cannot handle any other operation.
  • _Fork(): _Fork another process from the OS to handle each request. But the problem is that in this way we cannot handle a lot of requests at the same time.
  • Threads: We can start a new thread for each request but threaded programming is not a walk in the park! Apache is multithreaded and it creates a thread per request.
  • Event Loop: With using Event Loop we can handle the throng of requests without blocking the main execution runtime.

The Event Loop

First definition: The entity that handles external events and converts them to into callback invocations.

Second definition: A loop that picks events from the event queue and pushes their callbacks to call stack.

For understanding the event loop we need to know about a few concepts:

Call Stack

A first in last out simple data structure. Every time we call a function it pushes to the stack and every time we return from a function it pops out of the stack.

Node Event Queue

Sometimes it is called message queue or callback queue. The event loop pushes callbacks from the event queue to call stack.

#javascript #nodejs #event-loop

How does the Event Loop work in Node.js?
7.40 GEEK