我是node.js的新手,一直在尝试设置一个基本的服务器。
我有下面的代码运行,我得到一个"写结束后"错误。
Socket.html是一个基本的html文件,在主体中有一个hello world字符串。那份文件里什么都没有了。我试过使用"ReadFileSync"方法,这抛出了一套全新的错误,我不完全理解。
我将感谢任何帮助在这个问题上。我是这方面的新手,所以请对我宽容一点:)提前谢谢你!我已经验证了路径是正确的,并且缓冲区确实有数据。
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.substr(1);
path = "\" + path;
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
break;
case '\socket.html':
//console.log(path);
fs.readFile(__dirname + path, function(error, data){
if(error){
response.writeHead(404);
response.write("This domain is missing");
}
else{
console.log(data);
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data,"utf8");
}
});
break;
default:
response.writeHead(404);
response.write("This domain is missing");
break;
}
response.end();
});
server.listen (8001),
我认为当您从文件系统异步读取时,response.end()
方法在response.write()
之前被调用,我建议使用以下代码:
var http = require('http');
var url = require('url');
var fs = require('fs');
var server = http.createServer(function(request, response) {
var path = url.parse(request.url).pathname.substr(1);
path = "\" + path;
switch(path) {
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
response.end();
break;
case '\socket.html':
fs.readFile(__dirname + path, function(error, data) {
if(error) {
response.writeHead(404);
response.write("This domain is missing");
} else {
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data, "utf8");
}
response.end();
});
break;
default:
response.writeHead(404);
response.write("This domain is missing");
response.end();
break;
}
});