Skip to content

Commit e124955

Browse files
committed
Implement watch, fix #3
1 parent bcc3135 commit e124955

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

index.js

+20-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'use strict';
22

33
var extend = require('extend-shallow');
4+
var fs = require('fs');
45
var gutil = require('gulp-util');
56
var jsonServer = require('json-server');
67
var through = require('through2');
@@ -9,15 +10,32 @@ module.exports = function(options) {
910

1011
options = extend({
1112
hostname: 'localhost',
12-
port: 3000
13+
port: 3000,
14+
watch: false
1315
}, (options || {}));
1416

1517
var stream = through.obj(function(file, enc, callback) {
1618

1719
var server = jsonServer.create();
20+
var router = jsonServer.router(file.path);
21+
22+
if (options.watch) {
23+
fs.watch(file.path, function (event, changedFile) {
24+
if (event === 'change') {
25+
gutil.log(gutil.colors.magenta(file.path), 'has changed, reloading json-server database');
26+
try {
27+
router.db.object = JSON.parse(fs.readFileSync(file.path));
28+
} catch (err) {
29+
gutil.log('Unable to parse', gutil.colors.magenta(file.path));
30+
gutil.log(err);
31+
}
32+
}
33+
});
34+
gutil.log('Watching', gutil.colors.magenta(file.path));
35+
}
1836

1937
server.use(jsonServer.defaults)
20-
.use(jsonServer.router(file.path))
38+
.use(router)
2139
.listen(options.port, options.hostname)
2240
.on('listening', function() {
2341
gutil.log('JSON server started at', gutil.colors.cyan('http://' + options.hostname + ':' + options.port));

0 commit comments

Comments
 (0)