3 * https://github.com/shama/gaze
5 * Copyright (c) 2013 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) {
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 fs.readdirSync(filepath).map(function(file) {
136 return path.join(filepath, file);
137 }).filter(function(file) {
138 return globule.isMatch(self._patterns, file, self.options);
139 }).forEach(function(file) {
140 self.emit('added', file);
149 Gaze.prototype.close = function(_reset) {
151 _reset = _reset === false ? false : true;
152 Object.keys(self._watchers).forEach(function(file) {
153 self._watchers[file].close();
155 self._watchers = Object.create(null);
156 Object.keys(this._watched).forEach(function(dir) {
157 self._unpollDir(dir);
160 self._watched = Object.create(null);
161 setTimeout(function() {
163 self.removeAllListeners();
164 clearInterval(self._keepalive);
170 // Add file patterns to be watched
171 Gaze.prototype.add = function(files, done) {
172 if (typeof files === 'string') { files = [files]; }
173 this._patterns = helper.unique.apply(null, [this._patterns, files]);
174 files = globule.find(this._patterns, this.options);
175 this._addToWatched(files);
177 this._initWatched(done);
180 // Dont increment patterns and dont call done if nothing added
181 Gaze.prototype._internalAdd = function(file, done) {
183 if (helper.isDir(file)) {
184 files = [helper.markDir(file)].concat(globule.find(this._patterns, this.options));
186 if (globule.isMatch(this._patterns, file, this.options)) {
190 if (files.length > 0) {
191 this._addToWatched(files);
193 this._initWatched(done);
197 // Remove file/dir from `watched`
198 Gaze.prototype.remove = function(file) {
200 if (this._watched[file]) {
201 // is dir, remove all files
202 this._unpollDir(file);
203 delete this._watched[file];
205 // is a file, find and remove
206 Object.keys(this._watched).forEach(function(dir) {
207 var index = self._watched[dir].indexOf(file);
209 self._unpollFile(file);
210 self._watched[dir].splice(index, 1);
215 if (this._watchers[file]) {
216 this._watchers[file].close();
221 // Return watched files
222 Gaze.prototype.watched = function() {
223 return this._watched;
226 // Returns `watched` files with relative paths to process.cwd()
227 Gaze.prototype.relative = function(dir, unixify) {
229 var relative = Object.create(null);
230 var relDir, relFile, unixRelDir;
231 var cwd = this.options.cwd || process.cwd();
232 if (dir === '') { dir = '.'; }
233 dir = helper.markDir(dir);
234 unixify = unixify || false;
235 Object.keys(this._watched).forEach(function(dir) {
236 relDir = path.relative(cwd, dir) + path.sep;
237 if (relDir === path.sep) { relDir = '.'; }
238 unixRelDir = unixify ? helper.unixifyPathSep(relDir) : relDir;
239 relative[unixRelDir] = self._watched[dir].map(function(file) {
240 relFile = path.relative(path.join(cwd, relDir) || '', file || '');
241 if (helper.isDir(file)) {
242 relFile = helper.markDir(relFile);
245 relFile = helper.unixifyPathSep(relFile);
250 if (dir && unixify) {
251 dir = helper.unixifyPathSep(dir);
253 return dir ? relative[dir] || [] : relative;
256 // Adds files and dirs to watched
257 Gaze.prototype._addToWatched = function(files) {
258 for (var i = 0; i < files.length; i++) {
260 var filepath = path.resolve(this.options.cwd, file);
262 var dirname = (helper.isDir(file)) ? filepath : path.dirname(filepath);
263 dirname = helper.markDir(dirname);
265 // If a new dir is added
266 if (helper.isDir(file) && !(filepath in this._watched)) {
267 helper.objectPush(this._watched, filepath, []);
270 if (file.slice(-1) === '/') { filepath += path.sep; }
271 helper.objectPush(this._watched, path.dirname(filepath) + path.sep, filepath);
273 // add folders into the mix
274 var readdir = fs.readdirSync(dirname);
275 for (var j = 0; j < readdir.length; j++) {
276 var dirfile = path.join(dirname, readdir[j]);
277 if (fs.lstatSync(dirfile).isDirectory()) {
278 helper.objectPush(this._watched, dirname, dirfile + path.sep);
285 Gaze.prototype._watchDir = function(dir, done) {
289 this._watchers[dir] = fs.watch(dir, function(event) {
290 // race condition. Let's give the fs a little time to settle down. so we
291 // don't fire events on non existent files.
292 clearTimeout(timeoutId);
293 timeoutId = setTimeout(function() {
294 // race condition. Ensure that this directory is still being watched
295 // before continuing.
296 if ((dir in self._watchers) && fs.existsSync(dir)) {
302 return this._handleError(err);
307 Gaze.prototype._unpollFile = function(file) {
308 if (this._pollers[file]) {
309 fs.unwatchFile(file, this._pollers[file] );
310 delete this._pollers[file];
315 Gaze.prototype._unpollDir = function(dir) {
316 this._unpollFile(dir);
317 for (var i = 0; i < this._watched[dir].length; i++) {
318 this._unpollFile(this._watched[dir][i]);
322 Gaze.prototype._pollFile = function(file, done) {
323 var opts = { persistent: true, interval: this.options.interval };
324 if (!this._pollers[file]) {
325 this._pollers[file] = function(curr, prev) {
329 fs.watchFile(file, opts, this._pollers[file]);
331 return this._handleError(err);
337 // Initialize the actual watch on `watched` files
338 Gaze.prototype._initWatched = function(done) {
340 var cwd = this.options.cwd || process.cwd();
341 var curWatched = Object.keys(self._watched);
343 // if no matching files
344 if (curWatched.length < 1) {
345 // Defer to emitting to give a chance to attach event handlers.
346 setImmediate(function () {
347 self.emit('ready', self);
348 if (done) { done.call(self, null, self); }
349 self.emit('nomatch');
354 helper.forEachSeries(curWatched, function(dir, next) {
356 var files = self._watched[dir];
357 // Triggered when a watched dir has an event
358 self._watchDir(dir, function(event, dirpath) {
359 var relDir = cwd === dir ? '.' : path.relative(cwd, dir);
360 relDir = relDir || '';
362 fs.readdir(dirpath, function(err, current) {
363 if (err) { return self.emit('error', err); }
364 if (!current) { return; }
367 // append path.sep to directories so they match previous.
368 current = current.map(function(curPath) {
369 if (fs.existsSync(path.join(dir, curPath)) && fs.lstatSync(path.join(dir, curPath)).isDirectory()) {
370 return curPath + path.sep;
376 // race condition-- sometimes the file no longer exists
379 // Get watched files for this dir
380 var previous = self.relative(relDir);
382 // If file was deleted
383 previous.filter(function(file) {
384 return current.indexOf(file) < 0;
385 }).forEach(function(file) {
386 if (!helper.isDir(file)) {
387 var filepath = path.join(dir, file);
388 self.remove(filepath);
389 self.emit('deleted', filepath);
394 current.filter(function(file) {
395 return previous.indexOf(file) < 0;
396 }).forEach(function(file) {
397 // Is it a matching pattern?
398 var relFile = path.join(relDir, file);
399 // Add to watch then emit event
400 self._internalAdd(relFile, function() {
401 self.emit('added', path.join(dir, file));
408 // Watch for change/rename events on files
409 files.forEach(function(file) {
410 if (helper.isDir(file)) { return; }
411 self._pollFile(file, function(err, filepath) {
412 // Only emit changed if the file still exists
413 // Prevents changed/deleted duplicate events
414 if (fs.existsSync(filepath)) {
415 self.emit('changed', filepath);
423 // Return this instance of Gaze
424 // delay before ready solves a lot of issues
425 setTimeout(function() {
426 self.emit('ready', self);
427 if (done) { done.call(self, null, self); }
433 // If an error, handle it here
434 Gaze.prototype._handleError = function(err) {
435 if (err.code === 'EMFILE') {
436 return this.emit('error', new Error('EMFILE: Too many opened files.'));
438 return this.emit('error', err);