server.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. const http = require('http');
  2. const fs = require('fs');
  3. const port = 2222;
  4. const path = require('path');
  5. const public = path.join(__dirname, 'public');
  6. const htmlFile = 'public/index.html'; //Single page app file
  7. /* Allowed file types */
  8. const types = {
  9. txt: 'text/plain',
  10. json: 'text/json',
  11. css: 'text/css',
  12. gif: 'image/gif',
  13. jpg: 'image/jpeg',
  14. png: 'image/png',
  15. svg: 'image/svg+xml',
  16. ico: 'image/ico',
  17. js: 'application/javascript'
  18. };
  19. /* Simple media path validation for single page app */
  20. function getType(path) {
  21. if (path == '/' || path.indexOf(`.html`) != -1) return 'html';
  22. for (const type in types) {
  23. if (path.indexOf(`.${type}`) != -1) return type;
  24. }
  25. return false;
  26. }
  27. /* Server rules */
  28. const server = http.createServer((req, res) => {
  29. const path = req.url.toLowerCase();
  30. const mediaType = getType(path);
  31. if (! mediaType) res.writeHead(404).end('Not found');
  32. res.writeHead(200, {
  33. 'Cache-Control': 'max-age=31536000',
  34. 'Content-Type': mediaType == 'html' ? 'text/html' : types[mediaType]
  35. });
  36. const filePath = mediaType == 'html' ? htmlFile : public + path;
  37. res.end(fs.readFileSync(filePath));
  38. });
  39. server.listen(port, '127.0.0.1');
  40. console.info(`Server running on port ${port}`)