Easy creation of nodejs servers (7): Implementation of blocking operations, nodejs servers
Let's take a look at what is a blocking operation;
I simulate a sleep () method to delay hello star from printing for 10 seconds.
RequestHandlers. js
Copy codeThe Code is as follows:
Function start (){
Console. log ("Request handler 'start' was called .");
Function sleep (milliSeconds ){
Var startTime = new Date (). getTime ();
While (new Date (). getTime () <startTime + milliSeconds );
}
Sleep (10000 );
Return "Hello Start ";
}
Function upload (){
Console. log ("Request handler 'upload' was called .");
Return "Hello Upload ";
}
Exports. start = start;
Exports. upload = upload;
During the request/start operation, the printing is delayed for 10 seconds.
Requests/upload will not be affected.
Next we will conduct an experiment:
Enter http: // localhost: 8888/start in the address bar of the first browser window, but do not open it first!
In the address bar of the second browser window, enter http: // localhost: 8888/upload. Similarly, do not open it first!
In the first window ("/start"), press enter, and then quickly switch to the second window ("/upload") and press Enter.
Note:
Loading the/start URL takes 10 seconds, which is the same as we expected.
/Upload URL also took 10 seconds!
Yes, it does not perform operations similar to sleep () in the corresponding request processing program. What is the problem?
The reason is that start () contains the blocking operation. The image is "It blocks all other processing work ".
Node. js is single-threaded. It can process tasks in parallel without adding additional threads.
It implements parallel operations through event loop. We should make full use of this point-avoid blocking operations as much as possible, instead, use non-blocking operations more.
The next section describes how to implement non-blocking operations.