utils.js 876 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. const fs = require('fs');
  2. const path = require('path');
  3. const flatted = require('flatted');
  4. function tryParse(filePath, defaultValue) {
  5. let result;
  6. try {
  7. result = readJSON(filePath);
  8. } catch (ex) {
  9. result = defaultValue;
  10. }
  11. return result;
  12. }
  13. /**
  14. * Read json file synchronously using flatted
  15. *
  16. * @param {String} filePath Json filepath
  17. * @returns {*} parse result
  18. */
  19. function readJSON(filePath) {
  20. return flatted.parse(
  21. fs.readFileSync(filePath, {
  22. encoding: 'utf8',
  23. })
  24. );
  25. }
  26. /**
  27. * Write json file synchronously using circular-json
  28. *
  29. * @param {String} filePath Json filepath
  30. * @param {*} data Object to serialize
  31. */
  32. function writeJSON(filePath, data) {
  33. fs.mkdirSync(path.dirname(filePath), {
  34. recursive: true,
  35. });
  36. fs.writeFileSync(filePath, flatted.stringify(data));
  37. }
  38. module.exports = { tryParse, readJSON, writeJSON };