Introduction
Recently heard of node. js, many articles describe how excellent the event-driven model, application in the server development has a great advantage, itself is very emotional to go, decided to understand deeply, which also triggered some thinking about the program design, recorded.
What is node. js
node. js is defined on the official web: "A platform built on the chrome JavaScript runtime to build high-speed, scalable network programs." node. JS's event-driven , non-blocking I/O model makes it lightweight and efficient, making it the perfect choice for building data-intensive real-time programs that run on distributed devices. ”
Node. JS Event-driven
Simply put, there is only one thread, and all IO operations (network, file access, and so on) are asynchronous and respond to processing through callbacks.
What does node. js do?
Node. JS implements asynchronous interfaces for operations such as networks, files, databases, and so on, allowing developers to design programs that run on only one thread and are designed for high-performance, highly concurrent network programs.
If it is not implemented asynchronously, there are possible ways of handling a thread for each connection, how many threads are established for each of the connections, and each thread is independent of each other. At first glance, there's no problem with this, but it's a cost to know that threading is being created, and it's hard to deal with the number of connections that you're dealing with, creating threads that waste a lot of resources.
The disadvantage of node. js
As you can see from the previous article, node. JS's event-driven mechanism has a big advantage in IO-intensive applications, so consider another scenario, CPU-intensive applications (such as data encryption, compression). Because node. JS's code runs in one thread, the event loop is blocked in this case. Of course, node. JS also offers other mechanisms (nexttick,child_process, etc.) to address this scenario, but it seems that these implementations can be quite ugly.
Thinking about the program design
The sense that node. JS is designed to have an advantage in IO-intensive applications is worth referring to in programming, and if the following design is used in multi-threaded languages, does it have the advantage of event-driven and avoid the disadvantage of CPU-intensive scenarios?
The overall business logic is based on event-driven processing, which avoids the tedious and error-prone areas of many multithreaded operations.
The CPU-intensive scenario uses threading, and the main thread callbacks the results.
At last
To node. JS is just a simple understanding, not in-depth study, there is nothing to forget everyone do not spray.
From for notes (Wiz)
Thinking triggered by the node. JS Event-driven model