-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
49 lines (44 loc) · 1.16 KB
/
utils.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
const path = require('path')
const fs = require('fs')
module.exports = {
getPlaces,
addPlace
}
function getPlaces (cb) {
const filePath = path.join(__dirname, 'data.json')
fs.readFile(filePath, 'utf8', (err, contents) => {
if (err) {
cb(new Error('Unable to load file'))
return
}
try {
const parsedData = JSON.parse(contents)
cb(null, parsedData)
} catch (parseError) {
cb(new Error('Unable to parse data'))
}
})
}
function addPlace (newPlace, cb) {
getPlaces((err, placeData) => {
if (err) {
cb(new Error('Error loading original place file'))
return
}
const newId = placeData.places[placeData.places.length - 1].id + 1
placeData.places.push({ id: newId, ...newPlace })
try {
const placeString = JSON.stringify(placeData, null, 2)
const filePath = path.join(__dirname, 'data.json')
fs.writeFile(filePath, placeString, 'utf8', (err) => {
if (err) {
cb(new Error('problem writing to file'))
return
}
cb(null, newId)
})
} catch (stringifyError) {
cb(new Error('problem converting to JSON string'))
}
})
}