Node.js 中的非阻塞代码不起作用

发布于 2025-01-04 03:45:49 字数 734 浏览 0 评论 0原文

我正在尝试学习如何在 node.js 中创建非阻塞应用程序,但我的代码似乎不起作用。

非阻塞.js

var http = require('http');
var exec = require('child_process').exec;

var userRequests = 0;
http.createServer(function (request, response) {
    userRequests++;

    response.writeHead(200, {'Content-Type': 'text/plain'});

    if( userRequests == 1 ){
        exec("node wait.js", function(){
            response.write('Thanks for waiting!');
            response.end();
        });
    }
    else{
        response.write('Hello!');
        response.end();
    }
}).listen(8080);

console.log('Server start');

等待.js

var startTime = new Date().getTime();
while (new Date().getTime() < startTime + 15000);

I'm trying to learn how to create non-blocking applications in node.js but my code doesn't seem to be working.

nonblocking.js

var http = require('http');
var exec = require('child_process').exec;

var userRequests = 0;
http.createServer(function (request, response) {
    userRequests++;

    response.writeHead(200, {'Content-Type': 'text/plain'});

    if( userRequests == 1 ){
        exec("node wait.js", function(){
            response.write('Thanks for waiting!');
            response.end();
        });
    }
    else{
        response.write('Hello!');
        response.end();
    }
}).listen(8080);

console.log('Server start');

wait.js

var startTime = new Date().getTime();
while (new Date().getTime() < startTime + 15000);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

韶华倾负 2025-01-11 03:45:49

根据定义,您的示例涉及阻塞逻辑。它可能不是阻塞的主要进程,但它仍然有点违背了目的。

Node 使用事件循环,就像浏览器中的 JavaScript 一样。网络上有大量可用资源可用于学习 JavaScript 的工作原理。

我建议您看一下这些:

关键是节点中的一切都是由某种事件触发的。在您发布的示例代码中,该事件是生成的进程退出。但您不需要启动单独的进程来等待 15 秒。 所有节点的 API 都是事件驱动的,基于时间的事件实际上是 JavaScript 本身的一部分。

以下是您如何编写类似示例的示例:

var http = require('http'),
    userRequests = 0;

http.createServer(function (request, response) {
  userRequests++;

  response.writeHead(200, {'Content-Type': 'text/plain'});

  if( userRequests == 1 ){
    setTimeout(function(){
      response.write('Thanks for waiting!');
      response.end();
    }, 15000);
  }
  else{
    response.write('Hello!');
    response.end();
  }
}).listen(8080, function() {
  console.log('Server start');
});

您在评论中提到了文件。要发送文件,您可以这样做:

var http = require('http'),
    exec = require('child_process').exec,
    userRequests = 0;

http.createServer(function (request, response) {
  userRequests++;

  response.writeHead(200, {'Content-Type': 'text/plain'});

  if( userRequests == 1 ){
    var stream = fs.createReadStream('./somefile.txt');
    stream.on('data', function(data) {
      response.write(data);
    });
    stream.on('end', function() {
      response.end();
    });
  }
  else{
    response.write('Hello!');
    response.end();
  }
}).listen(8080, function() {
  console.log('Server start');
});

一般来说,它实际上更简单,因为您可以这样做:

if( userRequests == 1 ){
  fs.createReadStream('./somefile.txt').pipe(response);
}

Node 有一个“流”的标准定义,它会发出数据和结束事件,以及“管道”方法自动处理绑定我在上面的示例中手动添加的数据和事件处理程序。

正如我所说,首先阅读这些文章。它们非常有用,可以让您朝着正确的方向前进。

By definition, your example involves blocking logic. It may not be the main process that is blocking, but it still kind of defeats the purpose.

Node uses an event loop just like JavaScript in the browser. There are tons of available of resources all over the net for learning how JavaScript works.

I would recommend you take a look at these:

The key point is that everything in node is triggered by some kind of event. In the example code that you have posted, that event is the spawned process exiting. But you don't need to start a separate process to wait for 15 seconds. All of node's APIs are event driven, and time based events are actually part of JavaScript itself.

Here is an example of how you would write something like your example:

var http = require('http'),
    userRequests = 0;

http.createServer(function (request, response) {
  userRequests++;

  response.writeHead(200, {'Content-Type': 'text/plain'});

  if( userRequests == 1 ){
    setTimeout(function(){
      response.write('Thanks for waiting!');
      response.end();
    }, 15000);
  }
  else{
    response.write('Hello!');
    response.end();
  }
}).listen(8080, function() {
  console.log('Server start');
});

You mentioned files in your comment. To send a file you would do this:

var http = require('http'),
    exec = require('child_process').exec,
    userRequests = 0;

http.createServer(function (request, response) {
  userRequests++;

  response.writeHead(200, {'Content-Type': 'text/plain'});

  if( userRequests == 1 ){
    var stream = fs.createReadStream('./somefile.txt');
    stream.on('data', function(data) {
      response.write(data);
    });
    stream.on('end', function() {
      response.end();
    });
  }
  else{
    response.write('Hello!');
    response.end();
  }
}).listen(8080, function() {
  console.log('Server start');
});

In general, it's actually more straightforward because you would do this instead:

if( userRequests == 1 ){
  fs.createReadStream('./somefile.txt').pipe(response);
}

Node has a standard definition of a 'stream' which emits data and end events, among other things, and the 'pipe' method automatically handles binding the data and event handlers that I manually added in my example above.

As I said, start off by reading those articles. They are very useful and will get you headed in the right direction.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文