json.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict';
  2. var path = require('path');
  3. var _mkdirp;
  4. function getMkdirp() {
  5. if (!_mkdirp) {
  6. _mkdirp = require('mkdirp');
  7. }
  8. return _mkdirp;
  9. }
  10. var _fs;
  11. function getFS() {
  12. if (!_fs) {
  13. _fs = require('mz/fs');
  14. }
  15. return _fs;
  16. }
  17. exports.strictJSONParse = function (str) {
  18. var obj = JSON.parse(str);
  19. if (!obj || typeof obj !== 'object') {
  20. throw new Error('JSON string is not object');
  21. }
  22. return obj;
  23. };
  24. exports.readJSONSync = function(filepath) {
  25. if (!getFS().existsSync(filepath)) {
  26. throw new Error(filepath + ' is not found');
  27. }
  28. return JSON.parse(getFS().readFileSync(filepath));
  29. };
  30. exports.writeJSONSync = function(filepath, str, options) {
  31. options = options || {};
  32. if (!('space' in options)) {
  33. options.space = 2;
  34. }
  35. getMkdirp().sync(path.dirname(filepath));
  36. if (typeof str === 'object') {
  37. str = JSON.stringify(str, options.replacer, options.space) + '\n';
  38. }
  39. getFS().writeFileSync(filepath, str);
  40. };
  41. exports.readJSON = function(filepath) {
  42. return getFS().exists(filepath)
  43. .then(function(exists) {
  44. if (!exists) {
  45. throw new Error(filepath + ' is not found');
  46. }
  47. return getFS().readFile(filepath);
  48. })
  49. .then(function(buf) {
  50. return JSON.parse(buf);
  51. });
  52. };
  53. exports.writeJSON = function(filepath, str, options) {
  54. options = options || {};
  55. if (!('space' in options)) {
  56. options.space = 2;
  57. }
  58. if (typeof str === 'object') {
  59. str = JSON.stringify(str, options.replacer, options.space) + '\n';
  60. }
  61. return mkdir(path.dirname(filepath))
  62. .then(function() {
  63. return getFS().writeFile(filepath, str);
  64. });
  65. };
  66. function mkdir(dir) {
  67. return new Promise(function(resolve, reject) {
  68. getMkdirp()(dir, function(err) {
  69. if (err) {
  70. return reject(err);
  71. }
  72. resolve();
  73. });
  74. });
  75. }