SimpleServerHelper.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. 'use strict';
  2. const fs = require('fs');
  3. const path = require('path');
  4. class SimpleServerHelper {
  5. constructor(config, request, response) {
  6. this.settings = {
  7. ...{
  8. publicFolder: 'public',
  9. htmlIndexPath: 'public/index.html',
  10. html404Path: 'public/404.html',
  11. verbose: false,
  12. allowedFiles: {
  13. txt: 'text/plain',
  14. json: 'text/json',
  15. css: 'text/css',
  16. gif: 'image/gif',
  17. jpg: 'image/jpeg',
  18. png: 'image/png',
  19. svg: 'image/svg+xml',
  20. ico: 'image/ico',
  21. js: 'application/javascript',
  22. html: 'text/html',
  23. },
  24. },
  25. ...config
  26. };
  27. this.request = request;
  28. this.response = response;
  29. const uri = request.url.toLowerCase();
  30. const publicPath = path.join(__dirname, this.settings.publicFolder);
  31. this.mimeType = this.getType(uri);
  32. this.filePath = this.isHtml() ? this.settings.htmlIndexPath : publicPath + uri;
  33. }
  34. getType(path) {
  35. if (path == '/') return this.settings.allowedFiles['html'];
  36. const extension = path.split('.').pop().split('?').shift();
  37. return this.settings.allowedFiles[extension];
  38. }
  39. isHtml() {
  40. return this.mimeType == this.settings.allowedFiles['html'];
  41. }
  42. isValid() {
  43. return this.isHtml() || this.fileExist();
  44. }
  45. fileExist() {
  46. let exists = false
  47. try {
  48. exists = fs.existsSync(this.filePath);
  49. } catch (error) {
  50. if (this.settings.verbose) console.error(error);
  51. }
  52. return exists;
  53. }
  54. handleLogs(isValid) {
  55. if (this.settings.verbose) {
  56. if (isValid) console.info(new Date().toString() + ' ' + this.filePath);
  57. else console.error('Error accessing ' + this.request.url);
  58. }
  59. }
  60. writeHead(isValid) {
  61. if (isValid) {
  62. this.response.writeHead(200, {
  63. 'Cache-Control': 'max-age=31536000',
  64. 'Content-Type': this.mimeType
  65. });
  66. } else {
  67. this.response.writeHead(404, {
  68. 'Content-Type': this.settings.allowedFiles['html']
  69. });
  70. }
  71. }
  72. respond() {
  73. const isValid = this.isValid();
  74. this.writeHead(isValid);
  75. isValid ? fs.createReadStream(this.filePath).pipe(this.response)
  76. : fs.createReadStream(this.settings.html404Path).pipe(this.response);
  77. this.handleLogs(isValid);
  78. }
  79. };
  80. module.exports = {
  81. SimpleServerHelper
  82. };