我是node.js的新手,并且一直在尝试设置一个基本的服务器。
我运行下面的代码,然后收到“Write After End”错误。
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);
答案 0 :(得分:2)
我认为当您从FileSystem async中读取时,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;
}
});