config.js
1.92 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
"use strict";
var fs = require('fs');
var Utils = {
createBlank: function (path) {
fs.writeFileSync(path, "{}");
},
read: function (path) {
var data = fs.readFileSync(path),
json;
json = JSON.parse(data);
return json;
},
stringify: function (json) {
return JSON.stringify(json, null, " ");
},
write: function (conf, path) {
var data = Utils.stringify(conf);
fs.writeFileSync(path, data);
}
};
var Config = function (path) {
this.sep = "\.";
this.path = path;
try {
this.conf = Utils.read(path);
} catch (e) {
Utils.createBlank(path);
this.conf = Utils.read(path);
}
};
Config.prototype.get = function (key) {
var json = this.conf,
elements = key.split(this.sep),
exist = true;
if (!elements) {
return undefined;
}
elements.forEach(function (element) {
if (!json) {
exist = false;
return false;
}
json = json[element];
});
if (!exist) {
return undefined;
}
return json;
};
Config.prototype.put = function (key, value) {
var elements = key.split(this.sep),
json = this.conf,
last;
if (!elements) {
return false;
}
last = elements.pop();
elements.forEach(function (element) {
var obj = json[element];
if (!obj) {
obj = {};
json[element] = obj;
}
json = json[element];
});
json[last] = value;
return true;
};
Config.prototype.remove = function (key) {
var elements = key.split(this.sep),
json = this.conf,
last;
if (!elements) {
return false;
}
last = elements.pop();
elements.forEach(function (element) {
var obj = json[element];
if (!obj) {
obj = {};
json[element] = obj;
}
json = json[element];
});
delete json[last];
return true;
};
Config.prototype.save = function () {
Utils.write(this.conf, this.path);
};
Config.prototype.toString = function () {
return Utils.stringify(this.conf);
};
module.exports = Config;