Home Web Front-end JS Tutorial Node JS Internals

Node JS Internals

Nov 19, 2024 am 08:15 AM

Suppose you go to a restaurant and there is one single chef who promises that "I can cook for hundreds of people at the same time and none of you will go hungry", Sounds impossible, right? You can consider this single check as Node JS which manages all these multiple orders and still serves the food to all the customers.

Whenever you ask someone the question "What is Node JS?", a person always gets back the answer "Node JS is a runtime which is used to run JavaScript outside of the browser environment".

But, What does runtime mean?... The runtime environment is a software infrastructure in which code execution is written into a specific programming language. It has all the tools, libraries, and features to run code, handle errors, manage memory, and can interact with the underlying operating system or hardware.

Node JS has all of these.

  • Google V8 Engine to run the code.

  • Core libraries and APIs such as fs, crypto, http, etc.

  • Infrastructure like Libuv and the Event Loop to support asynchronous and non-blocking I/O operations.

So, we can now know why Node JS is called runtime.

This run time consists of two independent dependencies, V8 and libuv.

V8 is an engine that is also used in Google Chrome and it is developed and managed by Google. In Node JS it executes the JavaScript code. When we run the command node index.js then Node JS passes this code to the V8 engine. V8 processes this code, executes it, and provides the result. For example, if your code logs "Hello, World!" to the console, V8 handles the actual execution that makes this happen.

The libuv library contains the C code that enables access to the operating system when we want functionality such as networking, I/O operations, or time-related operations. It works as a bridge between Node JS and the operating system.

The libuv handles following operations:

  • File system operations: Reading or writing files (fs.readFile, fs.writeFile).

  • Networking: Handling HTTP requests, sockets, or connecting to servers.

  • Timers: Managing functions like setTimeout or setInterval.

Tasks like file reading are handled by the Libuv thread pool, timers by Libuv’s timer system, and network calls by OS-level APIs.

Is Node JS single-threaded?

Look at the following example.

const fs = require('fs');
const path = require('path');

const filePath = path.join(__dirname, 'file.txt');

const readFileWithTiming = (index) => {
  const start = Date.now();
  fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
      console.error(`Error reading the file for task ${index}:`, err);
      return;
    }
    const end = Date.now();
    console.log(`Task ${index} completed in ${end - start}ms`);
  });
};

const startOverall = Date.now();
for (let i = 1; i <= 4; i++) {
  readFileWithTiming(i);
}

process.on('exit', () => {
  const endOverall = Date.now();
  console.log(`Total execution time: ${endOverall - startOverall}ms`);
});

Copy after login
Copy after login
Copy after login

We are reading the same file four times and we are logging the time to read those files.

We get the following output of this code.

Task 1 completed in 50ms
Task 2 completed in 51ms
Task 3 completed in 52ms
Task 4 completed in 53ms
Total execution time: 54ms
Copy after login
Copy after login
Copy after login

We can see that we completed all four files reading almost at 50th ms. If Node JS is single-threaded then how are all these files reading operations completed at the same time?

This question answers that the libuv library uses the thread pool. the thread pool is a bunch of threads. By default, the thread pool size is 4 means 4 requests can be processed at once by libuv.

Consider another scenario where instead of reading one file 4 times we are reading this file 6 times.

const fs = require('fs');
const path = require('path');

const filePath = path.join(__dirname, 'file.txt');

const readFileWithTiming = (index) => {
  const start = Date.now();
  fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
      console.error(`Error reading the file for task ${index}:`, err);
      return;
    }
    const end = Date.now();
    console.log(`Task ${index} completed in ${end - start}ms`);
  });
};

const startOverall = Date.now();
for (let i = 1; i <= 4; i++) {
  readFileWithTiming(i);
}

process.on('exit', () => {
  const endOverall = Date.now();
  console.log(`Total execution time: ${endOverall - startOverall}ms`);
});

Copy after login
Copy after login
Copy after login

The output will look like:

Task 1 completed in 50ms
Task 2 completed in 51ms
Task 3 completed in 52ms
Task 4 completed in 53ms
Total execution time: 54ms
Copy after login
Copy after login
Copy after login

Node JS Internals

Suppose Read operation 1 and 2 completed and thread 1 and 2 become free.

Node JS Internals

You can see that the first 4 times we get almost the same time for reading the file but when we read this file the 5th and 6th time then it takes almost double the time to complete the read operations from the first four reading operations.

This happens because the thread pool size is by default 4 so four reading operations are handled at the same time but then again 2 (5th and 6th) times we are reading the file then libuv waits because all the threads have some work. When one of the four threads completes execution then 5th read operation is handled to that thread and the same for 6th time read operation will be done. that's the reason why it takes more time.

So, Node JS is not single-threaded.

But, why do some people refer to it as single-threaded?

This is because the main event loop is single-threaded. This thread is responsible for executing Node JS code, including handling asynchronous callbacks and coordinating tasks. It does not directly handle blocking operations like file I/O.

Code execution flow is like this.

  • Synchronous Code (V8):

Node.js executes all synchronous (blocking) code line by line using the V8 JavaScript engine.

  • Async Tasks Delegated:

Asynchronous operations like fs.readFile, setTimeout, or http requests are sent to the Libuv library or other subsystems (e.g., OS).

  • Task Execution:

Tasks like file reading are handled by the Libuv thread pool, timers by Libuv’s timer system, and network calls by OS-level APIs.

  • Callback Queued:

Once an async task is complete, its associated callback is sent to the event loop's queue.

  • Event Loop Executes Callbacks:

The event loop picks up callbacks from the queue and executes them one by one, ensuring non-blocking execution.

You can change the thread pool size using process.env.UV_THREADPOOL_SIZE = 8.

Now, I am thinking that if we set the high number of threads then we will able to handle the high number of requests also. I hope you will think like me about this.

But, It is the opposite of what we were thinking.

If we increase the number of threads beyond a certain limit then it will slow down your code execution.

Look at the following example.

const fs = require('fs');
const path = require('path');

const filePath = path.join(__dirname, 'file.txt');

const readFileWithTiming = (index) => {
  const start = Date.now();
  fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
      console.error(`Error reading the file for task ${index}:`, err);
      return;
    }
    const end = Date.now();
    console.log(`Task ${index} completed in ${end - start}ms`);
  });
};

const startOverall = Date.now();
for (let i = 1; i <= 4; i++) {
  readFileWithTiming(i);
}

process.on('exit', () => {
  const endOverall = Date.now();
  console.log(`Total execution time: ${endOverall - startOverall}ms`);
});

Copy after login
Copy after login
Copy after login

output:

With High Thread Pool Size (100 threads)

Task 1 completed in 50ms
Task 2 completed in 51ms
Task 3 completed in 52ms
Task 4 completed in 53ms
Total execution time: 54ms
Copy after login
Copy after login
Copy after login

Now, the following output is when we set the thread pool size as 4 (default size).

With Default Thread Pool Size (4 threads)

const fs = require('fs');
const path = require('path');

const filePath = path.join(__dirname, 'file.txt');

const readFileWithTiming = (index) => {
  const start = Date.now();
  fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
      console.error(`Error reading the file for task ${index}:`, err);
      return;
    }
    const end = Date.now();
    console.log(`Task ${index} completed in ${end - start}ms`);
  });
};

const startOverall = Date.now();
for (let i = 1; i <= 6; i++) {
  readFileWithTiming(i);
}

process.on('exit', () => {
  const endOverall = Date.now();
  console.log(`Total execution time: ${endOverall - startOverall}ms`);
});
Copy after login

You can see that the total execution time has a 100ms difference. the total execution time ( thread pool size 4) is 600ms and the total execution time (thread pool size 100) is 700ms. so, a thread pool size of 4 is taking less time.

Why the high number of threads != more tasks can be processed concurrently?

The first reason is that each thread has its own stack and resource requirement. If you increase the number of threads then ultimately it leads to out-of-memory or CPU resources conditions.

The second reason is that Operating systems have to schedule threads. If there are too many threads, the OS will spend a lot of time switching between them (context switching), which adds overhead and slows down the performance instead of improving it.

Now, we can say that it is not about increasing the thread pool size to achieve scalability and high performance but, It’s about using the right architecture, such as clustering, and understanding the task nature (I/O vs CPU-bound) and how Node.js’s event-driven model works.

Thank You for reading.

The above is the detailed content of Node JS Internals. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

See all articles