How to understand NodeJs’ non-blocking I/O

1 I/O: namelyInput/outputRefers to the inputs and outputs of a system

2 The main differences between non-blocking and blocking are:The ability to continue to receive other input between receiving input and output results.

example

Eat out There are usually two ways to eat out: 1. Go to the canteen to eat

  • [Wait in line] – [Wait for the person in front of you to get dinner] – [Help yourself to dinner] – [eat dinner]

2 Go to a restaurant

  • [Sit down] – [order] – [wait] – [eat]

In terms of the two ways of eating: 1 canteen eating: For the meal staff, they must wait for the first person to finish the meal before they serve another person. This process is the blocking mode 2 canteen eating: When you go to a restaurant to have a meal, the waiter will continue to deal with the next person’s order after ordering your meal. When your meal is ready, the waiter will send the meal to you. For the waiter, this process is a non-blocking process

Understand the essentials of non-blocking I/O

1 Identify a system that performs I/O operations. For example, in the meal example above, the system that performs I/O operations is the server. 2 Whether to perform other I/ OS during the I/O operation

Code demo

In the sample code we introduce a library called Glob, which is mainly used to find matching files. See www.npmjs.com/package/glo…

First, we use the synchronous method provided by glob to read the file

    const glob = require("glob");
    let result = null;
    result = glob.sync(__dirname + "/ / * * *");
    console.log(result);
Copy the code

The result is oneAn array of files:

Let’s take a look at the execution time of this synchronous operation:

    const glob = require("glob");

    let result = null;
    console.time("glob");
    result = glob.sync(__dirname + "/ / * * *");
    console.timeEnd("glob");
Copy the code

Results:

A file read operation will block the process for 33 milliseconds. This is unacceptable!

Next, we read the file asynchronously

    let result2 = null;
    console.time("glob2");
    glob(__dirname + "/ / * * *".(err, res) = > {
      console.log("glob over");
    });
    console.timeEnd("glob2");
Copy the code

Results:

It took 4 milliseconds to read the file asynchronously, and there are other things we can do while reading the file asynchronously.

conclusion

I believe you have a better understanding of non-blocking I/O. See you next time. Good good study, day day up!