-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.js
33 lines (31 loc) · 796 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
const homedir = require('os').homedir()
const home = process.env.HOME || homedir
const p = require('path')
const fs = require('fs')
const dbPath = p.join(home, '.todo')
const db = {
read(path = dbPath) {
return new Promise((resolve, reject) => {
fs.readFile(path, {flag: 'a+'}, (error, data) => {
if (error) return reject(error)
let list
try {
list = JSON.parse(data.toString())
} catch (error2) {
list = []
}
resolve(list)
})
})
},
write(list, path = dbPath) {
return new Promise((resolve) => {
const string = JSON.stringify(list)
fs.writeFile(path, string + '\n', (error) => {
if (error) return console.log(error)
resolve()
})
})
}
}
module.exports = db