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