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.

129 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. const path = require('path')
  8. module.exports=
  9. {
  10. /**
  11. * Method which return the contents of a file as a string
  12. * @param fileName
  13. * @return {*}
  14. */
  15. getFileContents: function(fileName)
  16. {
  17. try
  18. {
  19. return fs.readFileSync(fileName);
  20. }
  21. catch (e)
  22. {
  23. console.log("Could not find " + fileName);
  24. }
  25. return '';
  26. },
  27. /**
  28. *
  29. * @param fileName
  30. * @returns {any}
  31. */
  32. getFileAsJSON: function(fileName)
  33. {
  34. return JSON.parse(fs.readFileSync(fileName, 'utf8'));
  35. },
  36. /**
  37. * Returns all the contents of a file as a single line
  38. * with no break lines.
  39. *
  40. * @param fileName
  41. * @return {*}
  42. */
  43. getFileLine: function(fileName)
  44. {
  45. try
  46. {
  47. return fs.readFileSync(fileName, "utf8").split('\n').join('');
  48. }
  49. catch (e)
  50. {
  51. console.log("Could not find " + fileName);
  52. }
  53. return '';
  54. },
  55. /**
  56. * Function which is responsible for returning all post data.
  57. *
  58. * @param request sent by user in initial server call
  59. * @return the post data
  60. */
  61. getPostData: function(req)
  62. {
  63. return new Promise(function(resolve, reject)
  64. {
  65. if(req.method == 'POST')
  66. {
  67. var body = '';
  68. req.on('data', function (data)
  69. {
  70. body += data;
  71. //Kills request, don't steal my RAM!!
  72. //You can only download so much ram ;)
  73. if (body.length > 1e6)
  74. {
  75. req.connection.destroy();
  76. reject();
  77. }
  78. });
  79. req.on('end', function ()
  80. {
  81. resolve(body);
  82. });
  83. }
  84. else
  85. {
  86. resolve(0);
  87. }
  88. });
  89. },
  90. /**
  91. * Verifies the contents of the config file
  92. * and returns it. If the config is incomplete,
  93. * it terminates the program.
  94. *
  95. * @returns {*|any}
  96. */
  97. getConfig: function()
  98. {
  99. const configContents = ["PORT", "SESSION_SECRET",
  100. "CACHE", "ADMIN_CHECK"];
  101. var config = JSON.parse(fs.readFileSync('/src/config.json', 'utf8'));
  102. for(var i = 0; i < configContents.length; i++)
  103. {
  104. if(!config.hasOwnProperty(configContents[i]))
  105. {
  106. console.log("Missing config property: " + configContents[i]);
  107. process.exit(1);
  108. }
  109. }
  110. return config;
  111. }
  112. };