[英]what is the executing sequence of “switch case” in node js
I'm new to node.js, I met a strange issue when run a simple sample. 我是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);
when I visit 当我访问
http://localhost:8001/socket.html
backend log output as following: 后端日志输出如下:
Connection
1
2
5
4
Connection
1
5
In the browser, there is no output, the source of html is empty. 在浏览器中,没有输出,html的源为空。 Notice the log, I guess this maybe the response has already closed after log print "5", before log print "4". 注意日志,我想这可能是响应在日志打印“ 5”之后,在日志打印“ 4”之前已经关闭。
I can't understand why the log sequence is not "1245", could somebody explain this to me? 我不明白为什么日志顺序不是“ 1245”,有人可以向我解释一下吗?
The fs.readFile
method is asynchronous . fs.readFile
方法是异步的 。 When you call it, execution continues immediately after it (at the break
statement), and then proceeds to the console.log(5)
, and the response.end()
calls. 当您调用它时,执行将立即在它之后(在break
语句处)继续进行,然后继续执行console.log(5)
,并调用response.end()
。
Therefore, response.end()
is being called before the fs.readFile
callback gets a chance to execute. 因此,在fs.readFile
回调有机会执行之前 , fs.readFile
调用response.end()
。 You need to move the response.end()
call inside the callback. 您需要在回调内部移动response.end()
调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.