我是一个完整的节点新手,我遇到了一个问题:
var http = require("http");
var url = require('url');
var fs = require('fs');
var io = require('socket.io');
var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('Hello World');
break;
case '/socket.html':
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("This doesn't exist - 404");
console.log(error);
} else {
console.log('hi!'); // **************<---- I'm getting here
response.writeHead(404, {'Content-Type': 'text/html'});
response.write(data, 'utf8');
}
});
break;
default:
response.writeHead(404);
response.write("This page does not exist - 404");
console.log(path);
break;
}
response.end();
});
server.listen(8001);
io.listen(server);
我要进入'else'中的console.log(),但是response.write根本没有输出任何内容,如果我是console.log(数据)我得到的
答案 0 :(得分:1)
你应该在写完后调用.end。
response.writeHead(404, {'Content-Type': 'text/html'});
response.write(data, 'utf8');
response.end();
http://nodejs.org/api/http.html#http_response_end_data_encoding
答案 1 :(得分:1)
从my comment扩展:
fs.readFile()
是一个异步调用,这意味着它只会告诉Node尝试打开该文件,然后继续而不等待它。所以通过这段代码:
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("This doesn't exist - 404");
console.log(error);
} else {
console.log('hi!'); // **************<---- I'm getting here
response.writeHead(404, {'Content-Type': 'text/html'});
response.write(data, 'utf8');
}
});
response.end();
此代码的作用是:
(好的,我添加了最后一行)
为了做你想做的事,你有两个选择:
使用fs.readFileSync()
同步打开文件操作,这样您就可以进行熟悉的“线性”编程了:
try {
var data=fs.readFileSync(__dirname+path,{"encoding":"utf8"});
response.writeHead(200,{"Content-Type":"text/html"});
response.write(data,"utf8");
}catch(e){
response.writeHead(400,{"Content-Type":"text/plain"});
response.write("This doesn't exist - 404");
}
response.end();
在fs.readFile()
的回调函数中结束响应,而不是在服务器侦听器中:
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('Hello World');
response.end();/* here */
break;
case '/socket.html':
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("This doesn't exist - 404");
response.end(); /* here */
console.log(error);
} else {
console.log('hi!');
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data, 'utf8');
response.end(); /* here */
}
});
break;
default:
response.writeHead(404);
response.write("This page does not exist - 404");
response.end(); /* here */
console.log(path);
break;
}
//response.end(); <-- get rid of this line
另请注意,当文件打开成功时,我在writeHead()
调用中更改了404
to 200
,我猜这就是你的意思。