json.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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) {
  19. mkdirp.sync(path.dirname(filepath));
  20. if (typeof str === 'object') {
  21. str = JSON.stringify(str, null, 2) + '\n';
  22. }
  23. fs.writeFileSync(filepath, str);
  24. };
  25. exports.readJSON = function(filepath) {
  26. return fs.exists(filepath)
  27. .then(function(exists) {
  28. if (!exists) {
  29. throw new Error(filepath + ' is not found');
  30. }
  31. return fs.readFile(filepath);
  32. })
  33. .then(function(buf) {
  34. return JSON.parse(buf);
  35. });
  36. };
  37. exports.writeJSON = function(filepath, str) {
  38. if (typeof str === 'object') {
  39. str = JSON.stringify(str, null, 2) + '\n';
  40. }
  41. return mkdir(path.dirname(filepath))
  42. .then(function() {
  43. return fs.writeFile(filepath, str);
  44. });
  45. };
  46. function mkdir(dir) {
  47. return new Promise(function(resolve, reject) {
  48. mkdirp(dir, function(err) {
  49. if (err) {
  50. return reject(err);
  51. }
  52. resolve();
  53. });
  54. });
  55. }