-
Notifications
You must be signed in to change notification settings - Fork 1
/
store.js
37 lines (31 loc) · 860 Bytes
/
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
const electron = require('electron');
const path = require('path');
const fs = require('fs');
class Store {
constructor (options) {
this.path = path.join(electron.app.getPath('userData'), options.fileName + '.json');
try {
this.data = JSON.parse(fs.readFileSync(this.path));
} catch (error) {
this.data = options.defaults;
}
}
get (key) {
return this.data[key];
}
set (key, val, retryTimes = 0) {
this.data[key] = val;
try {
fs.writeFileSync(this.path, JSON.stringify(this.data));
} catch (error) {
if (retryTimes > 10) {
console.error('Failed to write too much, stopping');
return;
}
console.error('Can\'t write to file, retry in 5 seconds');
setTimeout(this.set, 5000, key, val, retryTimes + 1);
}
}
}
// expose the class
module.exports = Store;