|
1 | 1 | const fs = require('fs') |
2 | 2 | const path = require('path') |
| 3 | +const jph = require('json-parse-helpfulerror') |
3 | 4 | const _ = require('lodash') |
4 | 5 | const chalk = require('chalk') |
5 | 6 | const enableDestroy = require('server-destroy') |
@@ -189,25 +190,30 @@ module.exports = function (argv) { |
189 | 190 | // Watch .js or .json file |
190 | 191 | // Since lowdb uses atomic writing, directory is watched instead of file |
191 | 192 | const watchedDir = path.dirname(source) |
| 193 | + let readError = false |
192 | 194 | fs.watch(watchedDir, (event, file) => { |
193 | | -<<<<<<< HEAD |
194 | 195 | // https://github.com/typicode/json-server/issues/420 |
195 | 196 | // file can be null |
196 | 197 | if (file) { |
197 | 198 | const watchedFile = path.resolve(watchedDir, file) |
198 | 199 | if (watchedFile === path.resolve(source)) { |
199 | 200 | if (is.JSON(watchedFile)) { |
200 | | - var obj |
| 201 | + let obj |
201 | 202 | try { |
202 | | - obj = JSON.parse(fs.readFileSync(watchedFile)) |
| 203 | + obj = jph.parse(fs.readFileSync(watchedFile)) |
| 204 | + if (readError) { |
| 205 | + console.log(chalk.green(` Read error has been fixed :)`)) |
| 206 | + readError = false |
| 207 | + } |
203 | 208 | } catch (e) { |
204 | | - console.log('Error reading JSON file'); |
205 | | - console.dir(e); |
206 | | - return; |
| 209 | + readError = true |
| 210 | + console.log(chalk.red(` Error reading ${watchedFile}`)) |
| 211 | + console.error(e.message) |
| 212 | + return |
207 | 213 | } |
208 | | - |
| 214 | + |
209 | 215 | // Compare .json file content with in memory database |
210 | | - var isDatabaseDifferent = !_.isEqual(obj, app.db.getState()) |
| 216 | + const isDatabaseDifferent = !_.isEqual(obj, app.db.getState()) |
211 | 217 | if (isDatabaseDifferent) { |
212 | 218 | console.log(chalk.gray(` ${source} has changed, reloading...`)) |
213 | 219 | server && server.destroy() |
|
0 commit comments