-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathminidb.js
55 lines (48 loc) · 1.17 KB
/
minidb.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
const fs = require('fs');
class MiniDb {
constructor(name) {
this.basePath = `${__dirname}/data/${name}`;
if (!fs.existsSync(this.basePath)){
console.log('[MiniDb]', 'Create base directory:', this.basePath);
fs.mkdirSync(this.basePath);
}
}
get(id) {
const filePath = `${this.basePath}/${id}.json`;
try {
if (fs.existsSync(filePath)) {
const raw = fs.readFileSync(filePath, {
encoding: 'utf8',
flag: 'r'
});
return JSON.parse(raw) || null;
} else {
fs.writeFileSync(filePath, "{}", {
encoding: 'utf8',
mode: '666',
flag: 'w'
});
return {};
}
} catch (e) {
console.error('[MiniDb]', 'Write error:', filePath, e);
}
return null;
}
put(id, value) {
const filePath = `${this.basePath}/${id}.json`;
try {
const raw = JSON.stringify(value);
fs.writeFileSync(filePath, raw, {
encoding: 'utf8',
mode: '666',
flag: 'w'
});
return true;
} catch (e) {
console.error('[MiniDb]', 'Write error:', filePath, e);
return false;
}
}
}
module.exports = MiniDb;