File tree 1 file changed +20
-2
lines changed
1 file changed +20
-2
lines changed Original file line number Diff line number Diff line change 1
1
'use strict' ;
2
2
3
3
var extend = require ( 'extend-shallow' ) ;
4
+ var fs = require ( 'fs' ) ;
4
5
var gutil = require ( 'gulp-util' ) ;
5
6
var jsonServer = require ( 'json-server' ) ;
6
7
var through = require ( 'through2' ) ;
@@ -9,15 +10,32 @@ module.exports = function(options) {
9
10
10
11
options = extend ( {
11
12
hostname : 'localhost' ,
12
- port : 3000
13
+ port : 3000 ,
14
+ watch : false
13
15
} , ( options || { } ) ) ;
14
16
15
17
var stream = through . obj ( function ( file , enc , callback ) {
16
18
17
19
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
+ }
18
36
19
37
server . use ( jsonServer . defaults )
20
- . use ( jsonServer . router ( file . path ) )
38
+ . use ( router )
21
39
. listen ( options . port , options . hostname )
22
40
. on ( 'listening' , function ( ) {
23
41
gutil . log ( 'JSON server started at' , gutil . colors . cyan ( 'http://' + options . hostname + ':' + options . port ) ) ;
You can’t perform that action at this time.
0 commit comments