2

Im having problem with my app.js in node not displaying my html page but my html code instead. I don't really know what to do so some help would be greatly appreciated. I would like to be able to load html, javascript and css from my public folder. This is my app.js code:

var http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs")

http.createServer(function(request, response) {

var uri = url.parse(request.url).pathname
    , filename = path.join(process.cwd(), uri);

path.exists(filename, function(exists) {
  if(!exists) {
    response.writeHead(404, {"Content-Type": "text/plain"});
    response.write("404 Not Found\n");
    response.end();
    return;
}

if (fs.statSync(filename).isDirectory()) filename += 'public/index.html';

fs.readFile(filename, "binary", function(err, file) {
  if(err) {        
    response.writeHead(500, {"Content-Type": "text/plain"});
    response.write(err + "\n");
    response.end();
    return;
  }

  response.writeHead(200);
  response.write(file, "binary");
  response.end();
  });
 });
}).listen(process.env.PORT, process.env.IP);

console.log("Static file server running./\CTRL + C to shutdown");
  • 2
    Try `response.writeHead(200, {'Content-Type': 'text/html'})`; – spacebean Jan 16 '14 at 11:48
  • 1
    Depending on what file it is you're trying to load you need to adjust the content type: `text/html` or `text/css`, for example. – Andy Jan 16 '14 at 11:48
  • thank you! I think its loading css and javascript too even tho I only added respnse.writeHead(200, {"Content-Type": "text/html"}); because I was able to link it to a css file? –  Jan 16 '14 at 12:02
  • oh wait no. How do I display all .css files? I was only able to use css if they were internal in the html page. Do i just add response.writehead(200, {"Content-Type": "text/css"}); in the app.js some random place? also the same for javascript? –  Jan 16 '14 at 13:51
  • Possible duplicate of [Loading basic HTML in Node.js](http://stackoverflow.com/questions/4720343/loading-basic-html-in-node-js) – AliLotfi Apr 11 '17 at 16:20

1 Answers1

1

You are not specifying the content type, if you try:

fs.readFile(filename, "binary", function(err, file) {
if(err) {        
    response.writeHead(500, {"Content-Type": "text/plain"});
    response.write(err + "\n");
    response.end();
    return;
  }

  response.writeHead(200, {'Content-Type': 'text/html'});
  response.write(file, "binary");
  response.end();
  });
 });
}).listen(process.env.PORT, process.env.IP);

That should work. If you want to display the error page in html, you will want to update that content type as well.

spacebean
  • 1,554
  • 1
  • 10
  • 13
  • thanks! To display the error page in html would be awesome. I know how to write in html in the response.write(); but how do I direct it to a lets say 500.html error page? –  Jan 16 '14 at 11:55