-
-
Notifications
You must be signed in to change notification settings - Fork 133
/
storage-folder.js
59 lines (52 loc) · 1.31 KB
/
storage-folder.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
const path = require('path');
const fs = require('fs-plus');
module.exports = class StorageFolder {
constructor(containingPath) {
if (containingPath) {
this.path = path.join(containingPath, 'storage');
}
}
store(name, object) {
return new Promise((resolve, reject) => {
if (!this.path) return resolve();
fs.writeFile(
this.pathForKey(name),
JSON.stringify(object),
'utf8',
error => (error ? reject(error) : resolve())
);
});
}
load(name) {
return new Promise(resolve => {
if (!this.path) return resolve(null);
const statePath = this.pathForKey(name);
fs.readFile(statePath, 'utf8', (error, stateString) => {
if (error && error.code !== 'ENOENT') {
console.warn(
`Error reading state file: ${statePath}`,
error.stack,
error
);
}
if (!stateString) return resolve(null);
try {
resolve(JSON.parse(stateString));
} catch (error) {
console.warn(
`Error parsing state file: ${statePath}`,
error.stack,
error
);
resolve(null);
}
});
});
}
pathForKey(name) {
return path.join(this.getPath(), name);
}
getPath() {
return this.path;
}
};