Home  >  Article  >  Web Front-end  >  轻松创建nodejs服务器(8):非阻塞是如何实现的_node.js

轻松创建nodejs服务器(8):非阻塞是如何实现的_node.js

WBOY
WBOYOriginal
2016-05-16 16:25:511049browse

这节我们来了解一下nodejs实现非阻塞操作的方法。

我们先来修改一下 start的处理程序:

复制代码 代码如下:

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;

这段代码,创建了一个新的变量content(初始值为“empty”),执行“ls -lah”命令,将结果赋值给content,最后将content返回。

我们引入了一个新的Node.js模块,child_process,之所以用它,是为了实现一个既简单又实用的非阻塞操作:exec()。

那么exec()做了什么呢?

它从Node.js来执行一个shell命令。在上面的例子里,我们用它来获取当前目录下所有的文件(“ls -lah”),然后,当/startURL请求的时候将文件信息输出到浏览器中。

我们启动服务器,访问“http://localhost:8888/start”我们会发现页面输出的内容是 empty。

exec()发挥作用了,有了它,我们可以执行非常耗时的shell操作而无需迫使我们的应用停下来等待该操作。

虽然如此,但是页面输出的内容似乎不是我们想要的结果。

我们来分析一下原因:

我们的代码是同步执行的,这就意味着在调用exec()之后,Node.js会立即执行 return content ;

在这个时候,content仍然是“empty”,因为传递给exec()的回调函数还未执行到——因为exec()的操作是异步的。

下一节我们将介绍如何解决这个问题。

Statement:
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