Check if file is not null when watching dir

This commit is contained in:
typicode
2016-11-27 20:12:38 +01:00
parent edbb860300
commit 3f355b3ada

View File

@ -185,21 +185,25 @@ module.exports = function (argv) {
// Since lowdb uses atomic writing, directory is watched instead of file // Since lowdb uses atomic writing, directory is watched instead of file
const watchedDir = path.dirname(source) const watchedDir = path.dirname(source)
fs.watch(watchedDir, (event, file) => { fs.watch(watchedDir, (event, file) => {
const watchedFile = path.resolve(watchedDir, file) // https://github.com/typicode/json-server/issues/420
if (watchedFile === path.resolve(source)) { // file can be null
if (is.JSON(watchedFile)) { if (file) {
var obj = JSON.parse(fs.readFileSync(watchedFile)) const watchedFile = path.resolve(watchedDir, file)
// Compare .json file content with in memory database if (watchedFile === path.resolve(source)) {
var isDatabaseDifferent = !_.isEqual(obj, app.db.getState()) if (is.JSON(watchedFile)) {
if (isDatabaseDifferent) { var obj = JSON.parse(fs.readFileSync(watchedFile))
// Compare .json file content with in memory database
var isDatabaseDifferent = !_.isEqual(obj, app.db.getState())
if (isDatabaseDifferent) {
console.log(chalk.gray(` ${source} has changed, reloading...`))
server && server.destroy()
start()
}
} else {
console.log(chalk.gray(` ${source} has changed, reloading...`)) console.log(chalk.gray(` ${source} has changed, reloading...`))
server && server.destroy() server && server.destroy()
start() start()
} }
} else {
console.log(chalk.gray(` ${source} has changed, reloading...`))
server && server.destroy()
start()
} }
} }
}) })
@ -208,11 +212,13 @@ module.exports = function (argv) {
if (argv.routes) { if (argv.routes) {
const watchedDir = path.dirname(argv.routes) const watchedDir = path.dirname(argv.routes)
fs.watch(watchedDir, (event, file) => { fs.watch(watchedDir, (event, file) => {
const watchedFile = path.resolve(watchedDir, file) if (file) {
if (watchedFile === path.resolve(argv.routes)) { const watchedFile = path.resolve(watchedDir, file)
console.log(chalk.gray(` ${argv.routes} has changed, reloading...`)) if (watchedFile === path.resolve(argv.routes)) {
server && server.destroy() console.log(chalk.gray(` ${argv.routes} has changed, reloading...`))
start() server && server.destroy()
start()
}
} }
}) })
} }