-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStorage.js
74 lines (64 loc) · 1.78 KB
/
Storage.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
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
const fs = require('fs');
//const path = require('path');
class Storage{
constructor(stName,stExt='json'){
this._filename = `./${stName}.${stExt}`;
if(!fs.existsSync(this._filename)){
fs.writeFileSync(this._filename,'{}');
this._openStorage();
}else{
this._openStorage();
}
return this;
}
_openStorage(){
this.Store = JSON.parse(fs.readFileSync(this._filename));
for (const id in this.Store) {
this[id] = this.Store[id];
}
delete this.Store;
}
_saveStorage(){
var data = JSON.parse(JSON.stringify(this));
// remove _filename from data
delete data._filename;
fs.writeFileSync(this._filename,JSON.stringify(data));
}
setItem(name, value) {
if (typeof value == "function") {
value = value.toString();
}
if (typeof value == "object") {
value = JSON.stringify(value);
}
this[name] = value;
this._saveStorage();
}
getItem(name) {
if (typeof this[name] == "undefined") { return null; }
return this[name];
}
removeItem(name) {
delete this[name];
this._saveStorage();
}
clear() {
var thisvalue = Object.keys(this);
if(thisvalue.indexOf('_filename')!=-1){
delete thisvalue[thisvalue.indexOf('_filename')]
}else{}
for (const id of thisvalue) {
delete this[id];
}
this._saveStorage();
this._openStorage();
return null;
}
key(index) {
if (typeof index == "undefined") {
return Object.keys(this);
}
return Object.keys(this)[index];
}
}
module.exports = {Storage}