# Discover the Magic of Node.js

## What is node.js ?

Node.js is an open-source and cross-platform JavaScript runtime environment. Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser.

**Built on:**

* Chrome’s V8 JavaScript Engine
    
* Uses **libuv** for handling asynchronous I/O operations
    

## The V8 JavaScript Engine

V8 is the name of the JavaScript engine that powers Google Chrome. It's the thing that takes our JavaScript and executes it while browsing with Chrome. V8 is written in C++, and it's continuously improved. It is portable and runs on Mac, Windows, Linux and several other systems.

V8 is the JavaScript engi[ne i.e. it parses and ex](https://nodejs.org/en/learn/getting-started/the-v8-javascript-engine#the-v8-javascript-engine)ecutes JavaScript code. The DOM, and the other Web Platform APIs (they all makeup runtime environment) are provided by the browser.

Other browsers have their own JavaScript engine:

* Firefox has [**SpiderMonkey**](https://spidermonkey.dev/)
    
* Safari has [**JavaScriptCore**](https://developer.apple.com/documentation/javascriptcore) (also called Nitro)
    
* Edge was originally based on [**Chakra**](https://github.com/Microsoft/ChakraCore) but has more recently been [rebuilt using Chromium](https://support.microsoft.com/en-us/help/4501095/download-the-new-microsoft-edge-based-on-chromium) and the V8 engine.
    

and many others exist as well.

## libuv

**libuv** is a **C-based library** that provides **asynchronous I/O** in Node.js.  
It’s the **engine** behind Node’s **non-blocking I/O model**.

Node.js uses libuv to handle:

* File system operations (e.g., `fs.readFile`)
    
* Networking (HTTP, TCP)
    
* Timers (`setTimeout`)
    
* Child processes
    
* DNS
    

**libuv provides a thread pool and event loop** that handles these tasks **in the background**, while your main JS thread keeps executing code.

Here's a breakdown of how **libuv** works inside Node.js:

### 1\. **Event Loop**

* Core part of Node.js
    
* Keeps checking: “Is there something to do?”
    
* Runs your callbacks once async work is done
    

### 2\. **Thread Pool**

* For heavy/slow tasks like:
    
    * File reading/writing
        
    * DNS lookups
        
* Default: 4 threads (can be changed via `UV_THREADPOOL_SIZE`)
    

### 3\. **I/O Polling**

* Monitors sockets, file descriptors using system APIs (like `epoll`, `kqueue`, or `IOCP`)
    
* These don’t need threads — they're **non-blocking by nature**
    

## Real-Life Analogy : Construction Company

Imagine you're a **project manager** (Node.js event loop).  
You handle multiple clients (incoming tasks) and coordinate work.

* For simple, fast tasks (like taking orders), you do them directly.
    
* For big tasks (like building a house), you assign workers (libuv threads).
    
* While they work, you keep managing other incoming tasks.
    
* When a worker is done, they notify you (callback), and you deliver the result to the client.
    

Your team (libuv) makes you look like a multitasking genius, even though you're single-threaded.

### How libuv Handles an Async File Read

```coffeescript
const fs = require('fs');

console.log('Start');

fs.readFile('data.txt', 'utf8', (err, data) => {
  console.log('File read complete:', data);
});

console.log('End');
```

Behind the scenes:

1. JS thread reaches `fs.readFile` call.
    
2. Instead of blocking, it **hands the task to libuv**.
    
3. libuv uses **thread pool** to read file.
    
4. JS thread continues — prints “End”.
    
5. Once the file is read, libuv **signals the event loop**.
    
6. Event loop queues the callback → prints file content.
    

### `Simplified Flow Diagram`

```coffeescript
┌─────────────────────────────┐
│       JS Main Thread        │
└────────────┬────────────────┘
             ↓
      [Call to fs.readFile]
             ↓
┌────────────▼────────────┐
│        libuv            │
│ ┌─────────────────────┐ │
│ │     Thread Pool     │ │◄───── For CPU/I/O tasks
│ └─────────────────────┘ │
│ ┌─────────────────────┐ │
│ │   I/O Polling       │ │◄───── For sockets, timers
│ └─────────────────────┘ │
└────────────┬────────────┘
             ↓
     [Callback ready]
             ↓
     Event Loop triggers
             ↓
     [JS Callback executes]
```

### Final Takeaway:

> **Node.js is single-threaded in JavaScript, but libuv runs a multi-threaded party behind the scenes!**  
> This is how Node handles lots of concurrent I/O without being blocked.
