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.

134 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. const fs = require('fs');
  6. const 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 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. *
  49. * @param fileName
  50. * @return {*}
  51. */
  52. getFileLine: function(fileName)
  53. {
  54. try
  55. {
  56. return fs.readFileSync(fileName, "utf8").split('\n').join('');
  57. }
  58. catch (e)
  59. {
  60. console.log("Could not find " + fileName);
  61. }
  62. return '';
  63. },
  64. /**
  65. * Function which is responsible for returning all post data.
  66. *
  67. * @param request sent by user in initial server call
  68. * @return the post data
  69. */
  70. getPostData: function(req)
  71. {
  72. return new Promise(function(resolve, reject)
  73. {
  74. if(req.method == 'POST')
  75. {
  76. var body = '';
  77. req.on('data', function (data)
  78. {
  79. body += data;
  80. //Kills request, don't steal my RAM!!
  81. //You can only download so much ram ;)
  82. if (body.length > 1e6)
  83. {
  84. req.connection.destroy();
  85. reject();
  86. }
  87. });
  88. req.on('end', function ()
  89. {
  90. resolve(body);
  91. });
  92. }
  93. else
  94. {
  95. resolve(0);
  96. }
  97. });
  98. },
  99. /**
  100. * Displays 404 error to user
  101. *
  102. * @param result
  103. * @returns {*}
  104. */
  105. print404: function()
  106. {
  107. return this.include("includes/404.html");
  108. },
  109. /**
  110. * Displays 404 error to user
  111. *
  112. * @param result
  113. * @returns {*}
  114. */
  115. printWrongHost: function()
  116. {
  117. return this.include("includes/incorrectHost.html");
  118. }
  119. };