-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage-folder.js
More file actions
49 lines (42 loc) · 1.18 KB
/
storage-folder.js
File metadata and controls
49 lines (42 loc) · 1.18 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
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
}
}