json.js 1.6 KB

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