utils.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* eslint-disable no-magic-numbers */
  2. "use strict";
  3. const fsAsync = require("fs").promises;
  4. const fs = require("fs");
  5. const path = require("path");
  6. /**
  7. * Check for intersection two arrays
  8. * @param {Array} arr1 array to
  9. * @param {Array} arr2 second array to combare against
  10. * @returns {boolean} is intersecting
  11. */
  12. exports.arraysHasIntersect = (arr1, arr2) => {
  13. let data = Array.isArray(arr1) ? arr1 : [arr1];
  14. for (const item of data)
  15. if (arr2.indexOf(item) != -1) return true;
  16. return false;
  17. };
  18. /**
  19. * Check for intersection of array values against string
  20. * @param {string} string string to be checked for intersection
  21. * @param {string} arr1 values to check
  22. * @returns {boolean} is intersecting
  23. */
  24. exports.stringHasIntersect = (string, arr) => {
  25. arr.forEach(item => {
  26. if(string.indexOf(item) !== -1) return true;
  27. });
  28. return false;
  29. };
  30. /**
  31. * Load JSON file in async style
  32. * @param {string} path path to file
  33. * @param {string} encoding file encoding
  34. * @returns {Object|false} return false if failed or Object if successful
  35. */
  36. exports.loadJsonAsync = async (path, encoding = "utf8") => {
  37. let result = false;
  38. try {
  39. result = await fsAsync.readFile(path, encoding);
  40. }
  41. // eslint-disable-next-line no-empty
  42. catch (ex) { }
  43. if (result) result = JSON.parse(result);
  44. return result;
  45. };
  46. /**
  47. * Get full path string
  48. * @param {string} str1 resolve elem 1
  49. * @param {string} str2 relative path
  50. * @returns {string} full path
  51. */
  52. exports.getFullPath = (str1, str2) => path.resolve(str1, str2);
  53. /**
  54. * Load JSON file iin sync way
  55. * @param {string} path path to file
  56. * @param {string} encoding file encoding
  57. * @returns {Object|false} return false if failed or Object if successful
  58. */
  59. exports.loadJson = (path, encoding = "utf8") => {
  60. try {
  61. return JSON.parse(fs.readFileSync(path, encoding));
  62. } catch (err) {
  63. return false;
  64. }
  65. };
  66. /**
  67. * Save JSON file synchronously with format
  68. * @param {string} obj object to save
  69. * @param {string} path path
  70. * @returns {undefined|false} returns false if error happened
  71. */
  72. exports.saveJson = (obj, path) => {
  73. try {
  74. fs.writeFileSync(path, JSON.stringify(obj, null, "\t"));
  75. } catch (err) {
  76. return false;
  77. }
  78. };