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");
5
  • 2
    Try response.writeHead(200, {'Content-Type': 'text/html'}); Commented Jan 16, 2014 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. Commented Jan 16, 2014 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? Commented Jan 16, 2014 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? Commented Jan 16, 2014 at 13:51
  • Possible duplicate of Loading basic HTML in Node.js Commented Apr 11, 2017 at 16:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.