Nodejs server with site index fallback


/ Published in: JavaScript
Save to your folder(s)

Gives you an idea of how to fallback to an 'index' page if URL points to a directory. Not very refined - Will never return a "is directory" error


Copy this code and paste it in your HTML
  1. var sys = require("sys"),
  2. http = require("http"),
  3. url = require("url"),
  4. path = require("path"),
  5. fs = require("fs");
  6.  
  7. http.createServer(function(request, response) {
  8. var uri = url.parse(request.url).pathname;
  9. var filename = path.join(process.cwd(), uri);
  10. var req = false;
  11.  
  12. path.exists(filename, function(exists) {
  13. if(!exists) {
  14. response.writeHead(404, {"Content-Type": "text/plain"});
  15. response.write("404 Not Found\n");
  16. response.end();
  17. return;
  18. }
  19.  
  20. fs.readFile(filename, "binary", function(err, file) {
  21. if(err) {
  22. //If is directory, fallback to 'site index'
  23. if(err.errno == 21) {
  24. req = http.request({host:'localhost',port:8080,path:'/hub.html',method:'GET'}, function(res) {
  25. res.on('data', function(chunk) {
  26. response.writeHead(200);
  27. response.write(chunk, 'binary'); //vs response.write(''+chunk); to cast as String
  28. response.end();
  29. });
  30. });
  31. req.end();
  32. return;
  33. }
  34.  
  35. response.writeHead(500, {"Content-Type": "text/plain"});
  36. response.write(err + "\n");
  37. response.end();
  38. return;
  39. }
  40.  
  41. response.writeHead(200);
  42. response.write(file, "binary");
  43. response.end();
  44. });
  45. });
  46. }).listen(8080);
  47.  
  48. sys.puts("Server running at http://localhost:8080/");

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.