“0”的执行顺序是什么;开关箱”;在节点js中

what is the executing sequence of "switch case" in node js

本文关键字:开关箱 js 节点 是什么 执行 顺序      更新时间:2023-09-26

我是node.js的新手,在运行一个简单的示例时遇到了一个奇怪的问题。

var http = require("http");
var url = require('url');
var fs = require('fs');
var server = http.createServer(function(request, response){ 
    console.log('Connection');
    var path = url.parse(request.url).pathname;
    console.log(1);
    switch(path){
        case '/':
            response.writeHead(200, {'Content-Type': 'text/html'}); 
            response.write('hello world');
            break;
        case '/socket.html':
            console.log(2);
            fs.readFile(__dirname + path, function(error, data){
                if (error){
                    response.writeHead(404);
                    response.write("opps this doesn't exist - 404");
                    console.log(3);
                }
                else{
                    response.writeHead(200, {"Content-Type": "text/html"});
                    response.write(data, "utf8");
                    console.log(4);
                }
            });
            break;
        default:
            response.writeHead(404);
            response.write("opps this doesn't exist - 404");
            break;
    }
    console.log(5);
    response.end(); 
}); 
server.listen(8001); 

当我访问时

http://localhost:8001/socket.html

后端日志输出如下:

    Connection
    1
    2
    5
    4
    Connection
    1
    5

在浏览器中,没有输出,html的源为空。注意日志,我想这可能是在日志打印"5"之后,日志打印"4"之前,响应已经关闭。

我不明白为什么日志序列不是"1245",有人能解释一下吗?

fs.readFile方法是异步。当您调用它时,执行会在它之后立即继续(在break语句中),然后继续到console.log(5),然后response.end()调用。

因此,在fs.readFile回调获得执行机会之前,response.end()被调用。您需要将response.end()调用移动到回调中。