forked from typicode/lowdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileSync.js
35 lines (31 loc) · 914 Bytes
/
FileSync.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
const fs = require('graceful-fs')
const Base = require('./Base')
const readFile = fs.readFileSync
const writeFile = fs.writeFileSync
// Same code as in FileAsync, minus `await`
class FileSync extends Base {
read() {
// fs.exists is deprecated but not fs.existsSync
if (fs.existsSync(this.source)) {
// Read database
try {
const data = readFile(this.source, 'utf-8').trim()
// Handle blank file
return data ? this.deserialize(data) : this.defaultValue
} catch (e) {
if (e instanceof SyntaxError) {
e.message = `Malformed JSON in file: ${this.source}\n${e.message}`
}
throw e
}
} else {
// Initialize
writeFile(this.source, this.serialize(this.defaultValue))
return this.defaultValue
}
}
write(data) {
return writeFile(this.source, this.serialize(data))
}
}
module.exports = FileSync