为什么我不能在fs.readFile中使用response.write?

这是我的代码。

var server = http.createServer(function(request, response){ console.log('Connection'); var path = url.parse(request.url).pathname; path = path.substr(1); switch(path){ case '': response.writeHead(200, {'Content-Type':'text/html'}); response.end(); break; case 'socket.html': response.write("read file"); //works fs.readFile(__dirname + '\\' + path, function(error, data){ if (error){ response.writeHead(404); //this doesn't work } else{ response.writeHead(200, {'Content-Type':'text/html'}); //doesn't work response.write("OK"); //doesn't work } }); response.end(); break; default: response.writeHead(404); response.end(); break; } }); 

服务器侦听端口8001,当我访问http://myhost.com:8001/socket.html时 ,我只能看到“读取文件”。 响应中的方法似乎在callback函数readFile中被破坏。 有人可以告诉我为什么,给我一个解决scheme? 谢谢! (原谅我可怜的英语:))。

你太早结束反应了。 传递给readFile的函数是一个asynchronouscallback函数,它在整个switch语句之后运行。