Easy to create Nodejs server (8): How non-blocking is implemented _node.js

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.