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.

136 lines
2.8 KiB

  1. /**
  2. Utilities is a node modules created to make tasks like
  3. including html files easier for me programming.
  4. */
  5. //used for file io
  6. const fs = require('fs');
  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 fileName the file to append to the result
  14. */
  15. include: function(fileName)
  16. {
  17. return new Promise(function(resolve, reject)
  18. {
  19. try
  20. {
  21. resolve(fs.readFileSync(fileName));
  22. }
  23. catch (e)
  24. {
  25. console.log("Could not find " + fileName);
  26. resolve("");
  27. }
  28. });
  29. },
  30. /**
  31. * Method which return the contents of a file as a string
  32. * @param fileName
  33. * @return {*}
  34. */
  35. getFileContents: function(fileName)
  36. {
  37. try
  38. {
  39. return fs.readFileSync(fileName);
  40. }
  41. catch (e)
  42. {
  43. console.log("Could not find " + fileName);
  44. }
  45. return '';
  46. },
  47. /**
  48. * Returns all the contents of a file as a single line
  49. * with no break lines.
  50. *
  51. * @param fileName
  52. * @return {*}
  53. */
  54. getFileLine: function(fileName)
  55. {
  56. try
  57. {
  58. return fs.readFileSync(fileName, "utf8").split('\n').join('');
  59. }
  60. catch (e)
  61. {
  62. console.log("Could not find " + fileName);
  63. }
  64. return '';
  65. },
  66. /**
  67. * Function which is responsible for returning all post data.
  68. *
  69. * @param request sent by user in initial server call
  70. * @return the post data
  71. */
  72. getPostData: function(req)
  73. {
  74. return new Promise(function(resolve, reject)
  75. {
  76. if(req.method == 'POST')
  77. {
  78. var body = '';
  79. req.on('data', function (data)
  80. {
  81. body += data;
  82. //Kills request, don't steal my RAM!!
  83. //You can only download so much ram ;)
  84. if (body.length > 1e6)
  85. {
  86. req.connection.destroy();
  87. reject();
  88. }
  89. });
  90. req.on('end', function ()
  91. {
  92. resolve(body);
  93. });
  94. }
  95. else
  96. {
  97. resolve(0);
  98. }
  99. });
  100. },
  101. /**
  102. * Displays 404 error to user
  103. *
  104. * @param result
  105. * @returns {*}
  106. */
  107. print404: function()
  108. {
  109. return this.include("includes/html/404.html");
  110. },
  111. /**
  112. * Displays 404 error to user
  113. *
  114. * @param result
  115. * @returns {*}
  116. */
  117. printWrongHost: function()
  118. {
  119. return this.include("includes/html/incorrectHost.html");
  120. }
  121. };