utils.js 966 B

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