In this section, let’s learn about the methods of nodejs to implement non-blocking operations.
Let's first modify the start handler:
The code copy is 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 have 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 executes a shell command from 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 /startURL requests.
We start the server and visit "http://localhost:8888/start" and we will find that the content output on the page is empty.
exec() works, and with it we can perform very time-consuming shell operations without forcing our app to stop and wait for that operation.
Despite this, the content output of the page does not seem to be the result we want.
Let's analyze the reasons:
Our code is executed synchronously, which means that after calling exec(), Node.js will execute return content immediately;
At this time, the content is still "empty", because the callback function passed to exec() has not been executed yet - because the operation of exec() is asynchronous.
In the next section we will explain how to solve this problem.