How does Node.js handle multiple requests?

How does Node.js handle multiple requests?

Foreword

In the field of computer science, the concepts of concurrency and parallelism are often mentioned. However, these two terms are often conflated, leading to a lot of confusion among many people about their understanding. The editor of this article will help readers better understand their different characteristics and application scenarios through an in-depth analysis of concurrency and parallelism. At the same time, the article will also introduce the techniques and methods of how Node.js handles multiple requests efficiently.

What is concurrency

Concurrency means that two or more tasks can start, run, and complete during overlapping time periods. This does not necessarily mean that they will run simultaneously, but they can be interleaved so that at any given time, there is always one task running.

The following editor uses a simple example to explain the characteristics of concurrency in detail to readers:

Suppose that in a restaurant, there is a waiter who takes an order from the customer at table No. 1, and then the waiter waits in the kitchen for the customer at table No. 1 to prepare the meal, and then brings the meal to table No. 1.

After the waiter completes the order of the first table of guests, he goes to the next table of guest No. 2 to accept the order, and then goes to the kitchen to wait for the preparation to be completed. After the meal is ready, he hands the ordered meal to the guest.

Seeing this, readers may feel that this waiter’s approach is not efficient at all. He could have gone to the second table to order while waiting for the first order. According to the waiter’s current practice, he would place an order at the second table while waiting for the first order. Nothing can be done during this period of time before the meal is ready, which wastes a lot of time.

Let’s now modify the waiter’s approach. The modification is as follows:

The waiter will go to table 1 to take the order and hand it over to the kitchen, then return to table 2 to take the order and hand it over to the kitchen as well. In this case, the waiter does not wait for the order to be ready but continues to the next table to take the order until the food is ready. When the food is ready, waiters will serve it to all the guests at the table. In this case, the number of threads (waiters) is not increased, but the processing is accelerated by shortening the idle time. Processing multiple tasks at the same time is called concurrency.

For example: You are cooking and you get a phone call, so you answer the phone, and when you hear the stove alarm, you go back and turn off the stove, and then go back to the phone.

This example demonstrates the concept of concurrency very well. While cooking, be able to handle different events from the phone and the stove simultaneously. You can temporarily switch to another task without interrupting one task, and then return to the original task. This concurrent approach can improve efficiency and better cope with multiple tasks. (Do two things at the same time, but only one thing at a time)

What is parallelism

Parallelism means that two or more tasks can actually run simultaneously. In order to achieve this, these tasks must be able to run on independent CPUs or cores. Similarly, the editor will still use the example of cooking to explain to you what parallelism is:

For example: while you are cooking, you receive a phone call. Your family members answer the call and you continue cooking. No one between you and your family will interfere with the other. Two different things happen to two people. This It’s parallelism.

What is a single-threaded process?

A single-threaded process is one that executes programming instructions in a single sequence. Having said that, if an application has the following set of instructions:

Instruction A

Instruction B

Command C

If this set of instructions were executed in a single-threaded process, the execution process would look like this:

What is a multi-threaded process?

A multithreaded process executes programming instructions in multiple sequences. Therefore, instructions do not need to wait for execution unless multiple instructions are grouped in different sequences.

Why is Node.js single-threaded?

Node.js is a single-threaded platform. This means it can only handle one request at a time.

For example: The waiter takes the order from table 1 and passes it to the kitchen, then goes to table 2 to take the order. When taking the order from table 2, the food from table 1 is ready, but the waiter cannot go over immediately and deliver the food to table 1. The waiter must first complete the order from table 2 and then hand it to the kitchen, and then Then deliver the prepared meal to table No. 1.

The Node.js web server maintains a limited thread pool to serve client requests. Multiple clients make multiple requests to the Node.js server. Node.js receives these requests and puts them into an event queue. The Node.js server has an internal component called the Event Loop, which is an infinite loop that receives and processes requests. This event loop is single-threaded, that is, the event loop is a listener to the event queue.

How does Node.js handle multiple requests?

Node.js can easily handle multiple concurrent requests through an event-driven model.

When a client sends a request, a single thread sends that request to others. The current thread will not be busy processing the request. Servers have people working for them. The server sends the request to the worker, which further sends it to other servers and waits for the response. At the same time, if there is another request, the thread sends it to another worker and waits for the response from another server.

This way a single thread will always be available to receive the client’s request. It does not block requests.

Code for Node.js to implement multiple requests:

const http = require('http');

//Create an HTTP server object
const server = http.createServer((req, res) => {
  // handle the request
  if (req.url === '/') {
    //Set response headers
    res.writeHead(200, { 'Content-Type': 'text/plain' });

    //Send response data
    res.end('Hello, World!');
  } else if (req.url === '/about') {
    //Set response headers
    res.writeHead(200, { 'Content-Type': 'text/plain' });

    //Send response data
    res.end('About Us');
  } else {
    //Set response headers
    res.writeHead(404, { 'Content-Type': 'text/plain' });

    //Send response data
    res.end('Page Not Found');
  }
});

// Listen to port 3000
server.listen(3000, () => {
  console.log('Server listening on port 3000');
});

Summary

Overall, Node.js has advantages in handling multiple requests. It utilizes the characteristics of event-driven and non-blocking I/O to efficiently handle concurrent requests, providing fast response and good scalability. At the same time, by using appropriate tools and technologies, performance can be further optimized, concurrency can be controlled, and system reliability and stability can be improved.

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Vue entry skill treeNode.js and npmNode installation and configuration 39809 people are learning the system