2
0

simplehttpserver.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /**
  2. * a barebones HTTP server in JS
  3. * to serve three.js easily
  4. *
  5. * @author zz85 https://github.com/zz85
  6. *
  7. * Usage: node simplehttpserver.js <port number>
  8. *
  9. * do not use in production servers
  10. * and try
  11. * npm install http-server -g
  12. * instead.
  13. */
  14. var port = 8000,
  15. http = require('http'),
  16. urlParser = require('url'),
  17. fs = require('fs'),
  18. path = require('path'),
  19. currentDir = process.cwd();
  20. port = process.argv[2] ? parseInt(process.argv[2], 0) : port;
  21. function handleRequest(request, response) {
  22. var urlObject = urlParser.parse(request.url, true);
  23. var pathname = decodeURIComponent(urlObject.pathname);
  24. console.log('[' + (new Date()).toUTCString() + '] ' + '"' + request.method + ' ' + pathname + '"');
  25. var filePath = path.join(currentDir, pathname);
  26. fs.stat(filePath, function(err, stats) {
  27. if (err) {
  28. response.writeHead(404, {});
  29. response.end('File not found!');
  30. return;
  31. }
  32. if (stats.isFile()) {
  33. fs.readFile(filePath, function(err, data) {
  34. if (err) {
  35. response.writeHead(404, {});
  36. response.end('Opps. Resource not found');
  37. return;
  38. }
  39. response.writeHead(200, {});
  40. response.write(data);
  41. response.end();
  42. });
  43. } else if (stats.isDirectory()) {
  44. fs.readdir(filePath, function(error, files) {
  45. if (error) {
  46. response.writeHead(500, {});
  47. response.end();
  48. return;
  49. }
  50. var l = pathname.length;
  51. if (pathname.substring(l-1)!='/') pathname += '/';
  52. response.writeHead(200, {'Content-Type': 'text/html'});
  53. response.write('<!DOCTYPE html>\n<html><head><meta charset="UTF-8"><title>' + filePath + '</title></head><body>');
  54. response.write('<h1>' + filePath + '</h1>');
  55. response.write('<ul style="list-style:none;font-family:courier new;">');
  56. files.unshift('.', '..');
  57. files.forEach(function(item) {
  58. var urlpath = pathname + item,
  59. itemStats = fs.statSync(currentDir + urlpath);
  60. if (itemStats.isDirectory()) {
  61. urlpath += '/';
  62. item += '/';
  63. }
  64. response.write('<li><a href="'+ urlpath + '">' + item + '</a></li>');
  65. });
  66. response.end('</ul></body></html>');
  67. });
  68. }
  69. });
  70. }
  71. http.createServer(handleRequest).listen(port);
  72. require('dns').lookup(require('os').hostname(), function (err, addr, fam) {
  73. console.log('Running at http://' + addr + ((port === 80) ? '' : ':') + port + '/');
  74. })
  75. console.log('Three.js server has started...');
  76. console.log('Base directory at ' + currentDir);