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.

96 lines
2.2 KiB

  1. /**
  2. Utilities is a node modules created to make tasks like
  3. including html files easier for me programming.
  4. */
  5. const fs = require('fs');
  6. var Promise = require('promise');
  7. module.exports=
  8. {
  9. /**
  10. * A function similar to the include statement in PHP
  11. * This function writes a file to the output
  12. *
  13. * @param result the result that is sent to the user from node
  14. * @param fileName the file to append to the result
  15. */
  16. include: function(result, fileName)
  17. {
  18. return new Promise(function(resolve, reject)
  19. {
  20. try
  21. {
  22. result.write(fs.readFileSync(fileName));
  23. }
  24. catch (e)
  25. {
  26. console.log("Could not find " + fileName);
  27. }
  28. resolve();
  29. });
  30. },
  31. /**
  32. * Method which return the contents of a file as a string
  33. * @param fileName
  34. * @return {*}
  35. */
  36. getFileContents: function(fileName)
  37. {
  38. try
  39. {
  40. return fs.readFileSync(fileName);
  41. }
  42. catch (e)
  43. {
  44. console.log("Could not find " + fileName);
  45. }
  46. return 0;
  47. },
  48. /**
  49. * Function which is responsible for returning all post data.
  50. *
  51. * @param request sent by user in initial server call
  52. * @return the post data
  53. */
  54. getPostData: function(req)
  55. {
  56. return new Promise(function(resolve, reject)
  57. {
  58. if(req.method == 'POST')
  59. {
  60. var body = '';
  61. req.on('data', function (data)
  62. {
  63. body += data;
  64. //Kills request, don't steal my RAM!!
  65. //You can only download so much ram ;)
  66. if (body.length > 1e6)
  67. {
  68. req.connection.destroy();
  69. reject();
  70. }
  71. });
  72. req.on('end', function ()
  73. {
  74. resolve(body);
  75. });
  76. }
  77. else
  78. {
  79. resolve(0);
  80. }
  81. });
  82. },
  83. print404: function(result)
  84. {
  85. return this.include(result, "includes/404.html");
  86. }
  87. };