Why use node.js

https://jingyan.baidu.com/article/597a064322df37312a524346.html

In short, when programming with Node.js, any time-consuming operation must be done asynchronously to avoid blocking the current function. Because you are serving clients, and all code is always single-threaded and executed sequentially.

Many articles have mentioned that Node.js is single-threaded. However, such a statement is not rigorous and can even be said to be very irresponsible, because we will at least think of the following issues:

How does Node.js handle concurrent requests in a thread? How does Node.js perform asynchronous file I/O in a thread? How does Node.js reuse the processing power of multiple CPUs on the server? Network I/O

Node.js can indeed handle a large number of concurrent requests in a single thread, but this requires certain programming skills. Let's review the code at the beginning of the article. After executing the app.js file, the console will output immediately, and we will see "Hello, World" when we visit the web page.

This is because Node.js is event-driven, which means that its callback function will only be executed when the network request event occurs. When multiple requests come in, they will line up in a queue and wait for execution in turn.

This seems natural, but if you don't fully realize that Node.js runs on a single thread, and the callback function is executed synchronously, and the program is developed according to the traditional model, it will cause serious problems. For a simple example, the "Hello World" string here may be the result of running some other module. Assuming that the generation of "Hello World" is very time-consuming, it will block the callback of the current network request, causing the next network request to fail to be responded.

The solution is simple, just use an asynchronous callback mechanism. We can pass the response parameter used to generate the output result to other modules, and generate the output result asynchronously, and finally execute the real output in the callback function. The advantage of this is that the callback function of http.createServer will not block, so there will be no unresponsive requests.

Guess you like

Origin blog.csdn.net/myidea999/article/details/85248093
Recommended