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.

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