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.