我是 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”,有人可以向我解释一下吗?