-
Notifications
You must be signed in to change notification settings - Fork 2
/
watcher.js
89 lines (68 loc) · 1.91 KB
/
watcher.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* Starts watcher for recompiling/live refresh, exports nothing.
* @module watcher
*/
var _ = require( 'underscore' );
var path = require( 'path' );
var gaze = require( 'gaze' );
var request = require( 'request' );
var compilers = require( './compilers' );
var loader = require( './markdown-loader' );
// Start watcher
gaze( [
'**',
'!{bower_components,bower_components/**}'
], watching );
/**
* Callback for starting watcher, performs recompile and refresh on change.
* @param {Error} err
* @param {Object} watcher
*/
function watching( err, watcher ) {
if ( err ) throw err;
watcher.on( 'all', function( evt, filepath ) {
var changed = path.relative( process.cwd(), filepath );
var changed_ext = path.extname( changed );
console.log( evt, changed );
switch( changed_ext ) {
case '.md':
var type = path.dirname( changed );
var item = path.basename( changed ).split( '.' )[ 0 ];
if ( evt === 'deleted' ) {
delete loader.data[ type ][ item ];
compileRefresh( 'html' );
} else {
loader.load( [ type, item ], _.partial( compileRefresh, 'html' ) );
}
break;
case '.json':
case '.jade':
compileRefresh( 'html' );
break;
case '.styl':
compileRefresh( 'css' );
break;
case '.js':
compileRefresh( 'js' );
break;
default:
refresh( compilers.html.filename );
}
} );
}
/**
* Compile and livereload given type.
* @param {string} type
*/
function compileRefresh( type ) {
compilers[ type ].compile( _.partial( refresh, compilers[ type ].filename ) );
}
/**
* Send livereload request
* @param {string} filename
*/
function refresh( filename ) {
if ( _.isArray( filename ) ) filename = filename.join( ',' );
console.log( 'requesting refresh: ' + filename );
request( 'http://localhost:35729/changed?files=' + filename );
}