simplehttpserver.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. console.log(process.argv);
  21. port = process.argv[2] ? parseInt(process.argv[2], 0) : port;
  22. function handleRequest(request, response) {
  23. var urlObject = urlParser.parse(request.url, true);
  24. var pathname = decodeURIComponent(urlObject.pathname);
  25. console.log('[' + (new Date()).toUTCString() + '] ' + '"' + request.method + ' ' + pathname + '"');
  26. var filePath = path.join(currentDir, pathname);
  27. fs.stat(filePath, function(err, stats) {
  28. if (err) {
  29. response.writeHead(404, {});
  30. response.end('File not found!');
  31. return;
  32. }
  33. if (stats.isFile()) {
  34. fs.readFile(filePath, function(err, data) {
  35. if (err) {
  36. response.writeHead(404, {});
  37. response.end('Opps. Resource not found');
  38. return;
  39. }
  40. response.writeHead(200, {});
  41. response.write(data);
  42. response.end();
  43. });
  44. } else if (stats.isDirectory()) {
  45. fs.readdir(filePath, function(error, files) {
  46. if (error) {
  47. response.writeHead(500, {});
  48. response.end();
  49. return;
  50. }
  51. var l = pathname.length;
  52. if (pathname.substring(l-1)!='/') pathname += '/';
  53. response.writeHead(200, {'Content-Type': 'text/html'});
  54. response.write('<!DOCTYPE html>\n<html><head><meta charset="UTF-8"><title>' + filePath + '</title></head><body>');
  55. response.write('<h1>' + filePath + '</h1>');
  56. response.write('<ul style="list-style:none;font-family:courier new;">');
  57. files.unshift('.', '..');
  58. files.forEach(function(item) {
  59. var urlpath = pathname + item,
  60. itemStats = fs.statSync(currentDir + urlpath);
  61. if (itemStats.isDirectory()) {
  62. urlpath += '/';
  63. item += '/';
  64. }
  65. response.write('<li><a href="'+ urlpath + '">' + item + '</a></li>');
  66. });
  67. response.end('</ul></body></html>');
  68. });
  69. }
  70. });
  71. }
  72. http.createServer(handleRequest).listen(port);
  73. require('dns').lookup(require('os').hostname(), function (err, addr, fam) {
  74. console.log('Running at http://' + addr + ((port === 80) ? '' : ':') + port + '/');
  75. })
  76. console.log('Three.js server has started...');
  77. console.log('Base directory at ' + currentDir);