In this section, let's take a look at how Nodejs implements non-blocking operations.
Let's start by modifying the start handler:
Copy Code code as follows:
var exec = require ("child_process"). exec;
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 (the initial value is "empty"), executes 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 was used to implement a simple and practical non-blocking operation: EXEC ().
So what does exec () do?
It executes a shell command from the node.js. In the example above, we use it to get all the files in the current directory ("Ls-lah"), and then output the file information to the browser when the/starturl request.
We start the server, access "Http://localhost:8888/start" We will find the content of the page output is empty.
EXEC () works, with it, we can perform very time-consuming shell operations without forcing our application to stop and wait for the operation.
Nevertheless, the content of the page output does not seem to be the result we want.
Let's analyze Why:
Our code is executed synchronously, which means that after calling exec (), Node.js immediately executes the return content;
At this point, the content is still "empty" because the callback function passed to EXEC () has not yet been executed-because the operation of EXEC () is asynchronous.
In the next section, we'll explain how to solve this problem.