Easy creation of nodejs servers (7): Implementation of blocking operations, nodejs servers

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.