-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
36 lines (32 loc) · 802 Bytes
/
db.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
const homedir = require('os').homedir()
const home = process.env.HOME || homedir
const path = require('path')
const fs = require('fs')
const db = {
handleFilePath(filePath) {
return path.join(filePath || home, '.todoList')
},
read(filePath) {
return new Promise((s,r) => {
fs.readFile(db.handleFilePath(filePath), { flag: 'a+' }, (err, data) => {
if (err) return r(err)
let list
try {
list = JSON.parse(data.toString())
} catch (err) {
list = []
}
s(list)
})
})
},
write(list, filePath) {
return new Promise((s,r) => {
fs.writeFile(db.handleFilePath(filePath), JSON.stringify(list) + '\n', (err) => {
if (err) return r(err)
s()
})
})
}
}
module.exports = db