poll_watcher.js
2.52 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
'use strict';
const fs = require('fs');
const path = require('path');
const watch = require('@cnakazawa/watch');
const common = require('./common');
const EventEmitter = require('events').EventEmitter;
/**
* Constants
*/
const DEFAULT_DELAY = common.DEFAULT_DELAY;
const CHANGE_EVENT = common.CHANGE_EVENT;
const DELETE_EVENT = common.DELETE_EVENT;
const ADD_EVENT = common.ADD_EVENT;
const ALL_EVENT = common.ALL_EVENT;
/**
* Export `PollWatcher` class.
* Watches `dir`.
*
* @class PollWatcher
* @param String dir
* @param {Object} opts
* @public
*/
module.exports = class PollWatcher extends EventEmitter {
constructor(dir, opts) {
super();
opts = common.assignOptions(this, opts);
this.watched = Object.create(null);
this.root = path.resolve(dir);
watch.createMonitor(
this.root,
{
interval: (opts.interval || DEFAULT_DELAY) / 1000,
filter: this.filter.bind(this),
},
this.init.bind(this)
);
}
/**
* Given a fullpath of a file or directory check if we need to watch it.
*
* @param {string} filepath
* @param {object} stat
* @private
*/
filter(filepath, stat) {
return (
stat.isDirectory() ||
common.isFileIncluded(
this.globs,
this.dot,
this.doIgnore,
path.relative(this.root, filepath)
)
);
}
/**
* Initiate the polling file watcher with the event emitter passed from
* `watch.watchTree`.
*
* @param {EventEmitter} monitor
* @public
*/
init(monitor) {
this.watched = monitor.files;
monitor.on('changed', this.emitEvent.bind(this, CHANGE_EVENT));
monitor.on('removed', this.emitEvent.bind(this, DELETE_EVENT));
monitor.on('created', this.emitEvent.bind(this, ADD_EVENT));
// 1 second wait because mtime is second-based.
setTimeout(this.emit.bind(this, 'ready'), 1000);
}
/**
* Transform and emit an event comming from the poller.
*
* @param {EventEmitter} monitor
* @public
*/
emitEvent(type, file, stat) {
file = path.relative(this.root, file);
if (type === DELETE_EVENT) {
// Matching the non-polling API
stat = null;
}
this.emit(type, file, this.root, stat);
this.emit(ALL_EVENT, type, file, this.root, stat);
}
/**
* End watching.
*
* @public
*/
close(callback) {
Object.keys(this.watched).forEach(filepath => fs.unwatchFile(filepath));
this.removeAllListeners();
if (typeof callback === 'function') {
setImmediate(callback.bind(null, null, true));
}
}
};