Posted By

evilkyro1965 on 12/29/14


Tagged

nodejs


Versions (?)

NodeJS Serve Static Files


 / Published in: JavaScript
 

URL: http://www.hongkiat.com/blog/node-js-server-side-javascript/

NodeJS Serve Static Files

  1. var sys = require("sys"),
  2. my_http = require("http"),
  3. path = require("path"),
  4. url = require("url"),
  5. filesys = require("fs");
  6. my_http.createServer(function(request,response){
  7. var my_path = url.parse(request.url).pathname;
  8. var full_path = path.join(process.cwd(),my_path);
  9. path.exists(full_path,function(exists){
  10. if(!exists){
  11. response.writeHeader(404, {"Content-Type": "text/plain"});
  12. response.write("404 Not Found\n");
  13. response.end();
  14. }
  15. else{
  16. filesys.readFile(full_path, "binary", function(err, file) {
  17. if(err) {
  18. response.writeHeader(500, {"Content-Type": "text/plain"});
  19. response.write(err + "\n");
  20. response.end();
  21.  
  22. }
  23. else{
  24. response.writeHeader(200);
  25. response.write(file, "binary");
  26. response.end();
  27. }
  28.  
  29. });
  30. }
  31. });
  32. }).listen(8080);
  33. sys.puts("Server Running on 8080");

Report this snippet  

You need to login to post a comment.