-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_store.js
47 lines (38 loc) · 1.05 KB
/
json_store.js
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
const fs = require('fs');
exports.jsonStore = (() => {
let store = {};
let filename = "store.json"
const _readStore = async (name) =>{
filename = name;
try{
const data = fs.readFileSync(name, "utf-8");
store = JSON.parse(data);
}catch(err){
_writeStore();
}
}
const _writeStore = () =>{
const storeJSON = JSON.stringify(store);
fs.writeFileSync(filename, storeJSON);
}
const _clearStore = () => {
store = {};
_writeStore();
}
const _put = (key, data) => {
if(!key || !data) throw new Error ("Key and Data are required");
store[key.toString()]=data
_writeStore();
}
const _get = (key) => {
if(store === {}) _readStore();
return store[key];
}
return {
init: (name) => {_readStore(name)},
save: ()=>{_writeStore()},
clear: ()=>{_clearStore()},
put: (key, data)=>{_put(key,data)},
get: (key)=>{return _get(key)}
}
})();