Nearby lessons

10 of 21

⚡ Working of Node.js

📌 What is Node.js?

Node.js allows us to create applications using JavaScript that can run everywhere, not just in web browsers.

Originally, JavaScript was mainly used for websites to make them interactive.

Now, we can run JavaScript on desktops, mobile apps, and as a server, which means we can build backend applications using Node.js.

How Node.js Works?

To understand how Node.js works as a backend server, we first need to understand how a web server works.

🧵 Single Threaded Nature of JavaScript

Node.js uses JavaScript, which is single-threaded. JavaScript does not have multiple threads.

To handle multiple requests, Node.js can:

  1. Introduce multiple threads in JavaScript (this would change JavaScript's original meaning) – ❌
  2. Stick with single thread and handle multiple requests differently – ✅

⚡ Handling Multiple Requests

Node.js achieves handling multiple clients through:

  • Non-Blocking I/O
  • Asynchronous operations

Note: Node.js is not recommended for CPU-intensive tasks (heavy calculations, complex problems). It is best for I/O-intensive tasks such as fetching data from a server, accessing resources, or reading/writing files.

🔧 How Node.js Supports “Workers” Without Threads

Even though Node.js is single-threaded, it can handle multiple requests using libuv.

libuv is a library built for Node.js in C language that provides:

  • Non-blocking I/O operations
  • Access to system kernel’s multiple threads

So, Node.js itself doesn't use multiple threads directly, but the underlying system kernel (via libuv) manages multiple threads to handle I/O operations. This makes Node.js fast and flexible.

Node.js Environment
RUNTIME ACTIVE
console.log("Single-threaded but multi-tasking!");

setTimeout(() => console.log("Task 1 (Async) finished"), 1000);
setTimeout(() => console.log("Task 2 (Async) finished"), 500);

console.log("Main thread is free for other work...");
Terminal Output
Live Output Preview

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!HTTP Module in Node.js