The advantages and disadvantages of Node.js \

Node.js is single-threaded.

The upside is that

1) simple

2) High performance, avoiding frequent thread switching overhead

3) Small footprint, because it is a single thread, under heavy load, the memory footprint is still very low

3) Thread safety, no locking, unlocking, deadlocks and other issues

php

\

node.js

\

The bad is

How to solve high concurrency?

Node uses asynchronous IO and event-driven (callback) functions to solve this problem.

In general, high-concurrency solutions provide a multithreaded model that provides one thread per business logic, with system thread switches to compensate for the time overhead of synchronous I/O calls. Like Apache, one request per thread.

Node.js uses a single-threaded model, asynchronous requests for all I/ OS, avoids frequent context switching, and maintains an event queue when Node.js executes. During execution, the program enters an event loop waiting for the arrival of the next event. After each asynchronous I/O request is completed, it will be pushed to the event queue for execution.

Such as:

For a simple database access operation, the traditional approach is this

 res = db.query('SELECT * from some_table');
 res.output();
Copy the code

The thread blocks at the first line of code, waits for the query to return the result, and then continues processing. Due to database queries, disk reads and writes, network communications, etc. (so-called I/O) block times can be very high (relative to the CPU always frequency). For high concurrency access, on the one hand, threads are blocked for a long time, and on the other hand, new threads are constantly added to cope with new requests, which will waste a lot of system resources. Meanwhile, the increase of threads will also occupy a lot of CPU time to deal with memory context switch. How does Node.js handle this

[javascript]  view plain copy

  1. db.query(‘SELECT * from some_table’, function(res) {   
  2.    res.output();  
  3. });  

The second argument to query is a callback function. The process does not wait for the result to return when it reaches db.query, but continues to execute the following statement until it enters the event loop. The event is sent to the event queue when the database execution result is returned, and the previous callback function is not called until the thread enters the event loop. Node.js asynchro is event-based. All I/O, network communication, and database queries are executed in a non-blocking manner, and the returned results are processed by an event loop. Node.js processes only one event at a time, and immediately enters the event loop to check for subsequent events. This allows the CPU and memory to concentrate on one thing at a time, while trying to keep time-consuming I/O and other operations running in parallel.

\

Event loop mechanism

An event loop means that Node.js uses an event mechanism for all asynchronous operations, with a thread constantly checking the event queue.

All logic in Node.js is the callback function of the event, so Node.js is always in the event loop, and the program entry is the callback function of the first event in the event loop. An I/O request may be issued or an EMIT event may be emitted directly within the event callback function, which returns to the event loop after execution. The event loop checks for unprocessed events in the event queue until the program terminates. Node.js’s event loop is invisible to the developer and is implemented by the Libev library. Libev constantly checks for active event listeners that can be detected, and then exits the event loop and the program ends. \

As is shown in

\

Libuv is a high-performance event-driven library that encapsulates some of the underlying features of Windows and Unix platforms and provides developers with a unified API. Therefore, Node.js is single-threaded, asynchronous and non-blocking.

But after all, how do you fix the single-threaded defect? Is there asynchronous non-blocking and we can rest easy?

Isn’t.

1) CPU-intensive tasks have disadvantages

As mentioned above, NodeJS is a single thread with an event loop that handles all requests. As shown in the figure. In the event processing process, it will intelligently send some time-consuming operations involving IO and network communication to worker Threads for execution, and then call back after execution. This is the so-called asynchronous I/O non-blocking. However, it takes care of the non-IO, CPU-only operations, such as Fibonacci numbers. It’s a single thread, and you have to do one task after another, and the first one doesn’t finish, and the second one just waits. As a result, cpu-intensive tasks that require a lot of CPU may cause slow response of the so-called high performance and high concurrency Node.js server.

\

\

2) Unable to take advantage of the CPU’s multi-core

At first, threads were just a mechanism for allocating processing time to individual processors. But if the operating system itself supports multiple cpus/cores, then each thread can get a different CPU/ kernel, achieving true “parallel computing”. In this case, multithreaded programs can improve resource efficiency. Node.js is a single-threaded program that has only one Event loop and uses only one CPU/ kernel. At present, most servers are multi-CPU or multi-core. When the Event loop of Node.js program is occupied by CPU-intensive tasks, resulting in other tasks being blocked, there are still CPU/ kernel idle, resulting in a waste of resources. \

\

The solution

Using native modules or third-party modules, open up processes or subprocesses to handle these specific tasks.

3) If an exception is thrown, the entire project will be unavailable because it is single-threaded. But it all comes down to code, and bad code, no matter what system it is, will be broken, if not broken. The solution is to use tools such as PM2 to run? \

Nodejs and javascript

Nodejs itself is not a development language. It is a tool or platform that interprets and runs javascript on the server side. Coffeescript is part of the NodeJS architecture, which is a new development language, but it is intended to be eventually compiled into javascript.

Nodejs uses Google V8 to explain running javascript, but the code that the system actually executes is written in C++. All javascript does is call these apis. Therefore, there is no issue of execution efficiency.

\

\

3. Application scenarios of NodeJS

\

1, RESTful API

This is ideal for Node because you can build it to handle tens of thousands of connections. It still doesn’t require a lot of logic; It’s essentially just looking up some values from some database and putting them together into a response. Because the response is a small amount of text and the inbound request is a small amount of text, the traffic is low and a single machine can handle the API requirements of even the busiest companies. \

2. Real-time programs

Like chat services

Chat applications are the best example of Node.js’s strengths: lightweight, high traffic, and the ability to run data-intensive (albeit computatively low) cross-platform devices. Chat is also a great use case to learn because it is simple and covers most of the solutions that a typical Node.js will use by far.

3. Single-page APP

There are many ajax. The single-page mechanism seems to be very popular nowadays, such as phoneGap apps, and there are many examples of a single page.

\

.

\

In summary, NodeJS is suitable for high concurrency, I/O intensive, small business logic scenarios


\

Refer to the article

Misunderstanding about Node.js

Node.js threads and processes \

www.slideshare.net/mysqlops/no…

The weakness of Node.js is CPU intensive tasks

www.ruanyifeng.com/blog/2014/1…

Segmentfault.com/a/119000000… \

www.cnblogs.com/sysuys/p/34…

\