我试图让节点js服务器和客户端设置使用socket.io(Daniel Nill上的教程)
我在同一目录server.js
& socket.html
。
server.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(path);
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
break;
case '/socket.html':
console.log("Path: " + __dirname + path);
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("Error 1: opps this doesn't exist - 404");
console.log("With Error");
}else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data, "utf8");
console.log("Without Error");
}
});
break;
default:
response.writeHead(404);
response.write("Error 2: opps this doesn't exist - 404");
break;
}
response.end();
});
server.listen(8001);
socket.html
<html>
<head>This is the title</head>
<body>This is our socket.html file</body>
</html>
终端显示此输出
MacBook-Pro:nodejs ptamzz$ node server.js
Connection
/socket.html
Path: /Users/ptamzz/Documents/nodejs/socket.html
Without Error
但是当我尝试访问http://localhost:8001/socket.html
时,浏览器会抛出一个空白页。
根据我的理解,我不想在显示socket.html
时获取HTML文件console.log("Without Error")
的内容吗?
答案 0 :(得分:2)
出现这种情况是因为在/socket.html
路径的情况下,您使用异步方法(fs.readFile
)和回调,该回调在 response.end()
调用后被称为。因此,您首先结束响应,然后在节点完成读取文件的10ms内,调用response.write(data, "utf8");
。
要修复response.end()
response.write(data, "utf8");