Reputation: 17
im trying to run simple http server and when something is typed in the Url to respond with the html file ,but it
s not working.Here is the code
var http=require('http');
var fs=require('fs');
console.log("Starting");
var host="127.0.0.1";
var port=1337;
var server=http.createServer(function(request,response){
console.log("Recieved request:" + request.url);
fs.readFile("./htmla" + request.url,function(error,data){
if(error){
response.writeHead(404,{"Content-type":"text/plain"});
response.end("Sorry the page was not found");
}else{
response.writeHead(202,{"Content-type":"text/html"});
response.end(data);
}
});
response.writeHead(200,{"Content-Type":"text/plain"});
response.write("Hello World!");
response.end();
});
server.listen(port,host,function(){
console.log("Listening " + host + ":" + port);
});
My workspace is C:\xampp\htdocs\designs and the html file is in the path C:\xampp\htdocs\designs\htmla ,and i have a html file there and i want when it`s typed in the url to open.Noew it is not showing me error or the html file.Just showing the Hell World no matter what i type in the url.
Upvotes: 0
Views: 5574
Reputation: 5348
Its because the file read is asynchronous so the file is being output in the callback after the response is ended. The best solution would be to just remove the hello world lines.
var http=require('http');
var fs=require('fs');
console.log("Starting");
var host="127.0.0.1";
var port=1337;
var server=http.createServer(function(request,response){
console.log("Recieved request:" + request.url);
fs.readFile("./htmla" + request.url,function(error,data){
if(error){
response.writeHead(404,{"Content-type":"text/plain"});
response.end("Sorry the page was not found");
}else{
response.writeHead(202,{"Content-type":"text/html"});
response.end(data);
}
});
});
server.listen(port,host,function(){
console.log("Listening " + host + ":" + port);
});
Upvotes: 1