Easily create nodejs server (8) : how is non blocking implemented

  • 2020-05-07 19:10:35
  • OfStack

In this section, we'll look at how nodejs implements non-blocking operations.

Let's first modify the start handler:


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 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 an shell command from Node.js. In the above example, we used it to get all the files in the current directory (" ls-lah ") and then output the file information to the browser when requested by /startURL.

We start the server, visit "http: / / localhost: 8888 / start" we will find that the content of the page output is empty.

exec() works, and with it we can perform a very time-consuming shell operation without forcing our application to stop and wait for it.

Even so, the output of the page doesn't seem to be what we want.

Let's analyze 1 reasons:

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

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

In the next section we will show you how to solve this problem.


Related articles: