3 * https://github.com/shama/gaze
5 * Copyright (c) 2016 Kyle Robinson Young
6 * Licensed under the MIT license.
12 var util = require('util');
13 var EE = require('events').EventEmitter;
14 var fs = require('fs');
15 var path = require('path');
16 var globule = require('globule');
17 var helper = require('./helper');
19 // shim setImmediate for node v0.8
20 var setImmediate = require('timers').setImmediate;
21 if (typeof setImmediate !== 'function') {
22 setImmediate = process.nextTick;
28 // `Gaze` EventEmitter object to return in the callback
29 function Gaze (patterns, opts, done) {
33 // If second arg is the callback
34 if (typeof opts === 'function') {
42 opts.interval = opts.interval || 100;
43 opts.debounceDelay = opts.debounceDelay || 500;
44 opts.cwd = opts.cwd || process.cwd();
47 // Default done callback
48 done = done || function () {};
50 // Remember our watched dir:files
51 this._watched = Object.create(null);
54 this._watchers = Object.create(null);
56 // Store watchFile listeners
57 this._pollers = Object.create(null);
62 // Cached events for debouncing
63 this._cached = Object.create(null);
66 if (this.options.maxListeners != null) {
67 this.setMaxListeners(this.options.maxListeners);
68 Gaze.super_.prototype.setMaxListeners(this.options.maxListeners);
69 delete this.options.maxListeners;
72 // Initialize the watch on files
74 this.add(patterns, done);
77 // keep the process alive
78 this._keepalive = setInterval(function () {}, 200);
82 util.inherits(Gaze, EE);
84 // Main entry point. Start watching and call done when setup
85 module.exports = function gaze (patterns, opts, done) {
86 return new Gaze(patterns, opts, done);
88 module.exports.Gaze = Gaze;
90 // Override the emit function to emit `all` events
91 // and debounce on duplicate events per file
92 Gaze.prototype.emit = function () {
97 var filepath = args[1];
100 // If not added/deleted/changed/renamed then just emit the event
101 if (e.slice(-2) !== 'ed') {
102 Gaze.super_.prototype.emit.apply(self, args);
106 // Detect rename event, if added and previous deleted is in the cache
108 Object.keys(this._cached).forEach(function (oldFile) {
109 if (self._cached[oldFile].indexOf('deleted') !== -1) {
110 args[0] = e = 'renamed';
111 [].push.call(args, oldFile);
112 delete self._cached[oldFile];
118 // If cached doesnt exist, create a delay before running the next
119 // then emit the event
120 var cache = this._cached[filepath] || [];
121 if (cache.indexOf(e) === -1) {
122 helper.objectPush(self._cached, filepath, e);
123 clearTimeout(timeoutId);
124 timeoutId = setTimeout(function () {
125 delete self._cached[filepath];
126 }, this.options.debounceDelay);
127 // Emit the event and `all` event
128 Gaze.super_.prototype.emit.apply(self, args);
129 Gaze.super_.prototype.emit.apply(self, ['all', e].concat([].slice.call(args, 1)));
132 // Detect if new folder added to trigger for matching files within folder
134 if (helper.isDir(filepath)) {
135 // It's possible that between `isDir` and `readdirSync()` calls the `filepath`
136 // gets removed, which will result in `ENOENT` exception
141 files = fs.readdirSync(filepath);
143 // Rethrow the error if it's anything other than `ENOENT`
144 if (e.code !== 'ENOENT') {
151 files.map(function (file) {
152 return path.join(filepath, file);
153 }).filter(function (file) {
154 return globule.isMatch(self._patterns, file, self.options);
155 }).forEach(function (file) {
156 self.emit('added', file);
165 Gaze.prototype.close = function (_reset) {
167 Object.keys(self._watchers).forEach(function (file) {
168 self._watchers[file].close();
170 self._watchers = Object.create(null);
171 Object.keys(this._watched).forEach(function (dir) {
172 self._unpollDir(dir);
174 if (_reset !== false) {
175 self._watched = Object.create(null);
176 setTimeout(function () {
178 self.removeAllListeners();
179 clearInterval(self._keepalive);
185 // Add file patterns to be watched
186 Gaze.prototype.add = function (files, done) {
187 if (typeof files === 'string') { files = [files]; }
188 this._patterns = helper.unique.apply(null, [this._patterns, files]);
189 files = globule.find(this._patterns, this.options);
190 this._addToWatched(files);
192 this._initWatched(done);
195 // Dont increment patterns and dont call done if nothing added
196 Gaze.prototype._internalAdd = function (file, done) {
198 if (helper.isDir(file)) {
199 files = [helper.markDir(file)].concat(globule.find(this._patterns, this.options));
201 if (globule.isMatch(this._patterns, file, this.options)) {
205 if (files.length > 0) {
206 this._addToWatched(files);
208 this._initWatched(done);
212 // Remove file/dir from `watched`
213 Gaze.prototype.remove = function (file) {
215 if (this._watched[file]) {
216 // is dir, remove all files
217 this._unpollDir(file);
218 delete this._watched[file];
220 // is a file, find and remove
221 Object.keys(this._watched).forEach(function (dir) {
222 var index = self._watched[dir].indexOf(file);
224 self._unpollFile(file);
225 self._watched[dir].splice(index, 1);
230 if (this._watchers[file]) {
231 this._watchers[file].close();
236 // Return watched files
237 Gaze.prototype.watched = function () {
238 return this._watched;
241 // Returns `watched` files with relative paths to process.cwd()
242 Gaze.prototype.relative = function (dir, unixify) {
244 var relative = Object.create(null);
245 var relDir, relFile, unixRelDir;
246 var cwd = this.options.cwd || process.cwd();
247 if (dir === '') { dir = '.'; }
248 dir = helper.markDir(dir);
249 unixify = unixify || false;
250 Object.keys(this._watched).forEach(function (dir) {
251 relDir = path.relative(cwd, dir) + path.sep;
252 if (relDir === path.sep) { relDir = '.'; }
253 unixRelDir = unixify ? helper.unixifyPathSep(relDir) : relDir;
254 relative[unixRelDir] = self._watched[dir].map(function (file) {
255 relFile = path.relative(path.join(cwd, relDir) || '', file || '');
256 if (helper.isDir(file)) {
257 relFile = helper.markDir(relFile);
260 relFile = helper.unixifyPathSep(relFile);
265 if (dir && unixify) {
266 dir = helper.unixifyPathSep(dir);
268 return dir ? relative[dir] || [] : relative;
271 // Adds files and dirs to watched
272 Gaze.prototype._addToWatched = function (files) {
273 for (var i = 0; i < files.length; i++) {
275 var filepath = path.resolve(this.options.cwd, file);
277 var dirname = (helper.isDir(file)) ? filepath : path.dirname(filepath);
278 dirname = helper.markDir(dirname);
280 // If a new dir is added
281 if (helper.isDir(file) && !(dirname in this._watched)) {
282 helper.objectPush(this._watched, dirname, []);
285 if (file.slice(-1) === '/') { filepath += path.sep; }
286 helper.objectPush(this._watched, path.dirname(filepath) + path.sep, filepath);
288 // add folders into the mix
289 var readdir = fs.readdirSync(dirname);
290 for (var j = 0; j < readdir.length; j++) {
291 var dirfile = path.join(dirname, readdir[j]);
292 if (fs.lstatSync(dirfile).isDirectory()) {
293 helper.objectPush(this._watched, dirname, dirfile + path.sep);
300 Gaze.prototype._watchDir = function (dir, done) {
304 this._watchers[dir] = fs.watch(dir, function (event) {
305 // race condition. Let's give the fs a little time to settle down. so we
306 // don't fire events on non existent files.
307 clearTimeout(timeoutId);
308 timeoutId = setTimeout(function () {
309 // race condition. Ensure that this directory is still being watched
310 // before continuing.
311 if ((dir in self._watchers) && fs.existsSync(dir)) {
317 this._watchers[dir].on('error', function (err) {
318 self._handleError(err);
321 return this._handleError(err);
326 Gaze.prototype._unpollFile = function (file) {
327 if (this._pollers[file]) {
328 fs.unwatchFile(file, this._pollers[file]);
329 delete this._pollers[file];
334 Gaze.prototype._unpollDir = function (dir) {
335 this._unpollFile(dir);
336 for (var i = 0; i < this._watched[dir].length; i++) {
337 this._unpollFile(this._watched[dir][i]);
341 Gaze.prototype._pollFile = function (file, done) {
342 var opts = { persistent: true, interval: this.options.interval };
343 if (!this._pollers[file]) {
344 this._pollers[file] = function (curr, prev) {
348 fs.watchFile(file, opts, this._pollers[file]);
350 return this._handleError(err);
356 // Initialize the actual watch on `watched` files
357 Gaze.prototype._initWatched = function (done) {
359 var cwd = this.options.cwd || process.cwd();
360 var curWatched = Object.keys(self._watched);
362 // if no matching files
363 if (curWatched.length < 1) {
364 // Defer to emitting to give a chance to attach event handlers.
365 setImmediate(function () {
366 self.emit('ready', self);
367 if (done) { done.call(self, null, self); }
368 self.emit('nomatch');
373 helper.forEachSeries(curWatched, function (dir, next) {
375 var files = self._watched[dir];
376 // Triggered when a watched dir has an event
377 self._watchDir(dir, function (event, dirpath) {
378 var relDir = cwd === dir ? '.' : path.relative(cwd, dir);
379 relDir = relDir || '';
381 fs.readdir(dirpath, function (err, current) {
382 if (err) { return self.emit('error', err); }
383 if (!current) { return; }
386 // append path.sep to directories so they match previous.
387 current = current.map(function (curPath) {
388 if (fs.existsSync(path.join(dir, curPath)) && fs.lstatSync(path.join(dir, curPath)).isDirectory()) {
389 return curPath + path.sep;
395 // race condition-- sometimes the file no longer exists
398 // Get watched files for this dir
399 var previous = self.relative(relDir);
401 // If file was deleted
402 previous.filter(function (file) {
403 return current.indexOf(file) < 0;
404 }).forEach(function (file) {
405 if (!helper.isDir(file)) {
406 var filepath = path.join(dir, file);
407 self.remove(filepath);
408 self.emit('deleted', filepath);
413 current.filter(function (file) {
414 return previous.indexOf(file) < 0;
415 }).forEach(function (file) {
416 // Is it a matching pattern?
417 var relFile = path.join(relDir, file);
418 // Add to watch then emit event
419 self._internalAdd(relFile, function () {
420 self.emit('added', path.join(dir, file));
426 // Watch for change/rename events on files
427 files.forEach(function (file) {
428 if (helper.isDir(file)) { return; }
429 self._pollFile(file, function (err, filepath) {
431 self.emit('error', err);
434 // Only emit changed if the file still exists
435 // Prevents changed/deleted duplicate events
436 if (fs.existsSync(filepath)) {
437 self.emit('changed', filepath);
444 // Return this instance of Gaze
445 // delay before ready solves a lot of issues
446 setTimeout(function () {
447 self.emit('ready', self);
448 if (done) { done.call(self, null, self); }
453 // If an error, handle it here
454 Gaze.prototype._handleError = function (err) {
455 if (err.code === 'EMFILE') {
456 return this.emit('error', new Error('EMFILE: Too many opened files.'));
458 return this.emit('error', err);