Easy creation of nodejs server (8): How to implement non-blocking, nodejs Server

Source: Internet
Author: User

Easy creation of nodejs server (8): How to implement non-blocking, nodejs Server

This section describes how to implement non-blocking operations in nodejs.

Let's first modify the start handler:

Copy codeThe Code is as follows:
Var exec = require ("child_process" cmd.exe c;
Function start (){
Console. log ("Request handler 'start' was called .");
Var content = "empty ";
Exec ("ls-lah", function (error, stdout, stderr ){
Content = stdout;
});
Return content;
}
 
Function upload (){
Console. log ("Request handler 'upload' was called .");
Return "Hello Upload ";
}
 
Exports. start = start;
Exports. upload = upload;

This Code creates a new variable content (Initial Value: "empty"), runs the "ls-lah" command, assigns the result to the content, and finally returns the content.

We introduced a new Node. js module child_process, which is used to implement a simple and practical non-blocking operation: exec ().

So what does exec () do?

It runs a shell command from Node. js. In the above example, we use it to obtain all the files ("ls-lah") in the current directory, and then output the file information to the browser when/startURL requests.

When we start the server and access "http: // localhost: 8888/start", we will find that the output content on the page is empty.

Exec () plays a role. With it, we can execute a very time-consuming shell operation without forcing our application to stop and wait for this operation.

However, the output content of the page does not seem to be the expected result.

Let's analyze the cause:

Our code is executed synchronously, which means that after exec () is called, Node. js will immediately execute return content;

At this time, the content is still "empty", because the callback function passed to exec () has not been executed yet -- because the exec () operation is asynchronous.

The next section describes how to solve this problem.

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.