What is Node.js and what is the Event Loop

What is Node.js and what is the Event Loop
Reading Time: 2 minutes

What is Node.js?

Node.js (also known as just Node) is a JavaScript runtime environment to run server-side web applications without using a web browser. It uses an asynchronous, event-driven model which makes a really fast engine using single-threaded for async processing.
Node.js provides simplicity in development because of its non-blocking I/O and even-based model results in short response time and concurrent processing, unlike other frameworks where developers have to use thread management.
Node.js uses the V8 that provides the runtime environment in which JavaScript executes.

Node.js is a javascript runtime that makes it possible for us to write back-end of applications.

Some facts about Node.js

  • The node package manager (NPM) provides access to hundres of thousands of resuable packages.
  • There’s a huge community that maintains Node.js and third party packages
  • Node.js is portable. It is available on Microsoft Windows, MacOS, Linux and many others OS
  • Node.js is a single-threaded but it can support concurrency via the concept of event and callbacks.
  • Node.j uses the Observer pattern.

What is the Event Loop in Node.js

The Event Loop is what allows Node.js to perform non-blocking I/O operations despite the fact that is single-threaded.
Whenever a task gets completed, the Event Loop fires the corresponding event which signals the event-listener function to execute.
It is used to handle all the I/O operations in an asynchronous manner without blocking the main thread.

Whatever is async is managed by Event Loop using a queue and listener.

Node.js event loop
Image credits: https://dev.to/

So when an async function needs to be executed, the main thread sends it to a different thread allowing V8 to keep executing the main code. Event Loop involves different phases with specific tasks such as timers, pending callbacks, idle or prepare, poll, check, close callbacks with different FIFO queues. Also in between iterations it checks for async I/O or timers and shuts down cleanly if there aren’t any.

So for example, if some network call needs to happen it will be scheduled in the event loop instead of the main thread (single thread). And if there are multiple such I/O calls each one will be queued accordingly to be executed separately (other than the main thread).

Thus even though we have single-threaded, I/O operations are handled in a non-blocking way.

,

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Join 22 other subscribers

Leave a Reply