0
我是node.js的新手,運行一個簡單示例時遇到了一個奇怪的問題。節點js中「switch case」的執行順序是什麼
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」,有人可以向我解釋這一點嗎?
我沒有注意到。謝謝。 – yuyue007