Personal blog written from scratch using Node.js, Bootstrap, and MySQL. https://jrtechs.net
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
3.0 KiB

  1. /**
  2. * Main server file for the blog. This file is responsible for
  3. * creating the server and listening for clients. The main run
  4. * function parses the url and calls a sub module to make the
  5. * appropriate pages.
  6. */
  7. const http = require('http');
  8. const url = require('url');
  9. const express = require("express");
  10. const session = require('express-session');
  11. const includes = require('./includes/includes.js');
  12. const utils = require('./utils/utils.js');
  13. const map = require('./utils/generateSiteMap.js');
  14. map.main();
  15. const app = express();
  16. app.use(session({ secret: utils.getFileLine('../session_secret'), cookie: { maxAge: 6000000 }}));
  17. const port = 8000;
  18. const cache = require('memory-cache');
  19. /**
  20. * Parses the request url and calls correct JS files
  21. */
  22. app.use(function(request, res)
  23. {
  24. if(request.headers.host.includes("localhost:" + port) ||
  25. request.headers.host.includes("jrtechs.net"))
  26. {
  27. const filename = url.parse(request.url, true).pathname;
  28. //handles image requests
  29. if(filename.includes("/img/") || filename.includes(".jpg") || filename.includes(".png"))
  30. {
  31. require("./img/image.js").main(res, filename, cache);
  32. }
  33. else if(filename.includes("/css/") || filename.includes(".txt"))
  34. {
  35. includes.sendCSS(res, filename, cache)
  36. }
  37. else if(filename.includes("/downloads/"))
  38. {
  39. require("./downloads/downloads.js").main(res, filename, request);
  40. }
  41. else
  42. {
  43. var file = "";
  44. var html = cache.get(filename);
  45. res.writeHead(200, {'Content-Type': 'text/html'});
  46. if(html == null)
  47. {
  48. if(filename === '' || filename === '/')
  49. {
  50. file="./posts/homePage.js";
  51. }
  52. else
  53. {
  54. var urlSplit = filename.split("/");
  55. if(urlSplit.length >= 2 && urlSplit[1] === 'category') //single category page
  56. file = "./posts/category.js";
  57. else if(urlSplit.length >= 2 && urlSplit[1] === 'admin') //top secret admin page
  58. file = "./admin/admin.js";
  59. else
  60. file = "./posts/posts.js";
  61. }
  62. Promise.all([includes.printHeader(),
  63. require(file).main(filename, request),
  64. includes.printFooter()]).then(function(content)
  65. {
  66. res.write(content.join(''));
  67. res.end();
  68. cache.put(filename, content.join(''));
  69. }).catch(function(err)
  70. {
  71. console.log(err);
  72. throw err;
  73. });
  74. }
  75. else
  76. {
  77. res.write(html);
  78. res.end();
  79. }
  80. }
  81. }
  82. else
  83. {
  84. utils.printWrongHost(res);
  85. res.end();
  86. }
  87. });
  88. http.createServer(app).listen(port);