为什么这个简单的Node程序不是非阻塞的?

Why isn't this simple Node program non-blocking?

本文关键字:是非 Node 简单 为什么 程序      更新时间:2023-09-26

我已经安装了node,并且正在运行一些简单的'hello world'风格的程序,以便更好地掌握正在发生的事情。

我很困惑,为什么下面的代码似乎以阻塞的方式运行。当我在5秒后打开浏览器到localhost:8080时,屏幕上出现了"进程启动…"answers"进程完成。"我希望"进程开始"立即出现,然后"进程完成"在5秒后出现。关于超时为什么影响这两段代码,有什么想法吗?这段代码保存在一个名为'hello.js'的文件中,我只需使用'node hello.js'运行它。

var http = require('http');
http.createServer(function(request,response) {
    response.writeHead(200);
    response.write("Process started...");
    setTimeout(function() {
        response.write("Process complete.");
        response.end();
    }, 5000);
}).listen(8080);

您的浏览器很可能正在缓冲响应。试着用curl (curl -N http://localhost:8080)代替它,你会看到不同。