utils.js 892 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. var fs = require( 'fs' );
  2. var write = require( 'write' );
  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( fs.readFileSync( filePath, {
  23. encoding: 'utf8'
  24. } ) );
  25. },
  26. /**
  27. * Write json file synchronously using circular-json
  28. *
  29. * @method writeJSON
  30. * @param {String} filePath Json filepath
  31. * @param {*} data Object to serialize
  32. */
  33. writeJSON: function ( filePath, data ) {
  34. write.sync( filePath, flatted.stringify( data ) );
  35. }
  36. };