Home > Web Front-end > JS Tutorial > Create a nodejs server easily (8): How non-blocking is achieved_node.js

Create a nodejs server easily (8): How non-blocking is achieved_node.js

WBOY
Release: 2016-05-16 16:25:51
Original
1100 people have browsed it

In this section we will take a look at how nodejs implements non-blocking operations.

Let’s modify the start handler first:

Copy code The code 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 (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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template