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.

103 lines
2.1 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. * Method which return the contents of a file as a string
  11. * @param fileName
  12. * @return {*}
  13. */
  14. getFileContents: function(fileName)
  15. {
  16. try
  17. {
  18. return fs.readFileSync(fileName);
  19. }
  20. catch (e)
  21. {
  22. console.log("Could not find " + fileName);
  23. }
  24. return '';
  25. },
  26. /**
  27. *
  28. * @param fileName
  29. * @returns {any}
  30. */
  31. getFileAsJSON: function(fileName)
  32. {
  33. return JSON.parse(fs.readFileSync(fileName, 'utf8'));
  34. },
  35. /**
  36. * Returns all the contents of a file as a single line
  37. * with no break lines.
  38. *
  39. * @param fileName
  40. * @return {*}
  41. */
  42. getFileLine: function(fileName)
  43. {
  44. try
  45. {
  46. return fs.readFileSync(fileName, "utf8").split('\n').join('');
  47. }
  48. catch (e)
  49. {
  50. console.log("Could not find " + fileName);
  51. }
  52. return '';
  53. },
  54. /**
  55. * Function which is responsible for returning all post data.
  56. *
  57. * @param request sent by user in initial server call
  58. * @return the post data
  59. */
  60. getPostData: function(req)
  61. {
  62. return new Promise(function(resolve, reject)
  63. {
  64. if(req.method == 'POST')
  65. {
  66. var body = '';
  67. req.on('data', function (data)
  68. {
  69. body += data;
  70. //Kills request, don't steal my RAM!!
  71. //You can only download so much ram ;)
  72. if (body.length > 1e6)
  73. {
  74. req.connection.destroy();
  75. reject();
  76. }
  77. });
  78. req.on('end', function ()
  79. {
  80. resolve(body);
  81. });
  82. }
  83. else
  84. {
  85. resolve(0);
  86. }
  87. });
  88. },
  89. };