In this section we will take a look at how nodejs implements non-blocking operations.
Let’s modify the start handler first:
This code creates a new variable content (initial value is "empty"), executes the "ls -lah" command, assigns the result to content, and finally returns 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 above example, 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 is requested.
We start the server and visit "http://localhost:8888/start" and we will find that the output content of the page is empty.
exec() comes into play. With it, we can perform very time-consuming shell operations without forcing our application to stop and wait for the operation.
Even so, the content output by 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, content is still "empty" because the callback function passed to exec() has not yet been executed - because the operation of exec() is asynchronous.
We will introduce how to solve this problem in the next section.