/
watcher.js
90 lines (74 loc) · 2.35 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
var fs = require('fs')
, events = require('events')
, util = require('util')
, minDuration = 1000
, lastChange
, watchers = { }
;
function watch(file, eventName, update) {
var fullPath = file.fullPath;
if (watchers[fullPath]) return;
watchers[fullPath] = true;
fs.watch(fullPath, { persistent: true }, function (event) {
if (event !== eventName) return;
// Avoid duplicate fires in cases when two change events are raised for one actual change
var now = new Date();
if (!lastChange || now - lastChange > minDuration) {
update(file);
lastChange = now;
}
});
}
function Watcher (templateFiles, partialFiles, templateDirectories) {
this.templateFiles = templateFiles;
this.partialFiles = partialFiles;
this.templateDirectories = templateDirectories;
}
util.inherits(Watcher, events.EventEmitter);
Watcher.prototype.watchTemplatesAndPartials = function () {
var self = this;
function keepWarm(file, process) {
watch(file, 'change', function (file) {
fs.readFile(file.fullPath, function (err, content) {
if (err) process(err);
else process(file, content.toString());
});
});
}
function watchTemplates(watchingAll) {
self.templateFiles.forEach(function (file) {
keepWarm(file, function (err, plate) {
// TODO: if error emit it
self.emit('templateChanged', file, plate);
self.emit('fileChanged', file, plate);
});
});
}
function watchPartials() {
self.partialFiles.forEach(function (file) {
keepWarm(file, function (err, partial) {
self.emit('partialChanged', file, partial);
self.emit('fileChanged', file, partial);
});
});
}
function watchDirectories() {
self.templateDirectories.forEach(function (directory) {
watch(directory, 'rename', function (file) {
self.emit('directoryChanged', directory);
});
});
}
watchTemplates();
watchPartials();
watchDirectories();
};
module.exports = {
create: function (templateFiles, partialFiles, templateDirectories) {
var watcher = new Watcher(templateFiles, partialFiles, templateDirectories);
watcher.watchTemplatesAndPartials();
return watcher;
}
// used for easy testing
, _overrideMinDuration: function (value) { minDuration = value; return this; }
};