preface

Sum up:

  • Understand node.js event polling
  • Node mini-application: node-sample

Wise men read books and experience life

The body of the

Two basic concepts of Node.js

The first basic concept of Node.js is that I/O operations are expensive:

So, the biggest waste in technology today comes from waiting for I/O operations to complete. There are several ways to address the performance impact:

  • synchronously: Process requests one by one in order.the: simple;The disadvantagesAny one request can block all other requests.
  • Start a new processEach request starts a new process.the: simple;The disadvantages: Lots of links means lots of processes.
  • Start a new threadEach request starts a new thread.the: simple, and more kernel friendly than processes, because threads are much lighter than processes;The disadvantagesNot all machines support threads, and multithreaded programming can quickly become too complex to handle shared resources.

The second basic concept is that creating a new thread for each connection is memory intensive (for example, you can recall Apache running out of memory compared to Nginx).

Apache is multithreaded: it starts a new thread (or process, depending on your configuration) for each request, and you can see how it runs out of memory bit by bit as the number of concurrent connections increases. Nginx and Node.js are not multithreaded because thread consumption is too “heavy”. Both are single-threaded, event-based, which eliminates the thread/process cost of handling many connections.

Single thread

There really is only one thread: you can’t execute any code in parallel, for example: the following “sleep” will block sever1 second:

function sleep() {
   var now = new Data().getTime();
   while (new Date().getTime() < now + 1000) {
         // do nothing
   }
}
sleep();Copy the code

However, as far as I am concerned, I think many people have a misconception about the so-called Node single thread. In fact, the official term “single thread” is misleading. A single thread means that your code runs on only one thread (in many places it is called the main thread, in fact Javascript browser runtime environment is not the same as we write Javascript code), but many tasks in parallel processing, need multithreading, as shown in the following figure:

As shown above, the single thread in Node.js refers to the main thread, which has a loop structure that keeps the entire program (the code you write) running.

Event polling

The part of the loop that keeps the main thread running is called “event polling”, which exists in the main thread and is responsible for constantly calling the code written by the developer. But it’s not visible to the developer. so… How does the code written by the developer get called? See below:

Pictured above, an asynchronous function at the end of the execution, will add an event on the event queue (follow the principle of first in first out), the main thread of the code execution after (that is, the end of a cycle), the next cycle start “read” event in the event queue, and then call it corresponds to the callback function (so that the callback function execution sequence is not necessarily). If the developer calls a blocking method in the callback (such as the sleep function above), the entire event polling will block and events in the event queue will not be processed in time. Because of this, some library methods in NodeJS are asynchronous, and users are encouraged to invoke asynchronous methods.

var fs = require('fs');
fs.readFile('hello.txt'.function (err, data) {  // Read files asynchronously
  console.log("read file end");
});
while(1)
{
    console.log("call readFile over");
}Copy the code

In the code above, although we use the asynchronous readFile method to read the file, the read File End is never printed because the code is always in the while loop, and the next event polling never starts, so there is no way to ‘read’ the event queue to call the corresponding callback function.

Finally, there is a Node-sample which is some codes accumulated by bloggers, including annotations, and summarized into a small application, which can still see the hints of learning. You can have a look if you are interested.

Afterword.

Reference article:

  • Understanding the node.js event loop
  • Nodejs event polling details