用工小程序前端代码
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.

44 lines
966 B

9 months ago
  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. };