-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
65 lines (53 loc) · 1.69 KB
/
index.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
var tinylr = require('tiny-lr');
var express = require('express');
var Gaze = require('gaze').Gaze;
var cors = require('cors');
var path = require('path');
var injectLivereload = require('./src/inject-livereload');
var urlCallback = require('./src/url-callback');
module.exports = Barkeep;
function Barkeep(root) {
if (!(this instanceof Barkeep)) {
return new Barkeep(root);
}
this._addToGaze = this._addToGaze.bind(this);
this.root = path.resolve(root);
this.server = tinylr();
this.app = express();
this.gaze = new Gaze(null, { debounceDelay: 200 });
this.watchedFiles = [];
}
Barkeep.prototype.listen = function(staticPort, lrPort, done) {
// Optionally accept the callback as either the first or second argument
if (typeof staticPort === 'function') {
done = staticPort;
staticPort = null;
} else if (typeof lrPort === 'function') {
done = lrPort;
lrPort = null;
}
staticPort = staticPort || 9091;
lrPort = lrPort || 35729;
this.server.listen(lrPort);
this.gaze.on('changed', function(filepath) {
this.server.changed({ body: { files: filepath.replace(this.root, '') } });
}.bind(this));
return this.app
.use(cors())
.use(injectLivereload(lrPort))
.use(urlCallback(this._addToGaze))
.use(express.static(this.root))
.listen(staticPort, done);
};
// Add a file to be watched for changes
Barkeep.prototype._addToGaze = function(url) {
// If it's a directory, add index.html to the end
if (/\/$/.test(url)) {
url += 'index.html';
}
if (this.watchedFiles.indexOf(url) === -1) {
this.watchedFiles.push(url);
this.gaze.add(path.join(this.root, url));
console.log('Added:', url, 'to list of watched files');
}
};