gaze.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. /*
  2. * gaze
  3. * https://github.com/shama/gaze
  4. *
  5. * Copyright (c) 2013 Kyle Robinson Young
  6. * Licensed under the MIT license.
  7. */
  8. 'use strict';
  9. // libs
  10. var util = require('util');
  11. var EE = require('events').EventEmitter;
  12. var fs = require('fs');
  13. var path = require('path');
  14. var globule = require('globule');
  15. var helper = require('./helper');
  16. // shim setImmediate for node v0.8
  17. var setImmediate = require('timers').setImmediate;
  18. if (typeof setImmediate !== 'function') {
  19. setImmediate = process.nextTick;
  20. }
  21. // globals
  22. var delay = 10;
  23. // `Gaze` EventEmitter object to return in the callback
  24. function Gaze(patterns, opts, done) {
  25. var self = this;
  26. EE.call(self);
  27. // If second arg is the callback
  28. if (typeof opts === 'function') {
  29. done = opts;
  30. opts = {};
  31. }
  32. // Default options
  33. opts = opts || {};
  34. opts.mark = true;
  35. opts.interval = opts.interval || 100;
  36. opts.debounceDelay = opts.debounceDelay || 500;
  37. opts.cwd = opts.cwd || process.cwd();
  38. this.options = opts;
  39. // Default done callback
  40. done = done || function() {};
  41. // Remember our watched dir:files
  42. this._watched = Object.create(null);
  43. // Store watchers
  44. this._watchers = Object.create(null);
  45. // Store watchFile listeners
  46. this._pollers = Object.create(null);
  47. // Store patterns
  48. this._patterns = [];
  49. // Cached events for debouncing
  50. this._cached = Object.create(null);
  51. // Set maxListeners
  52. if (this.options.maxListeners) {
  53. this.setMaxListeners(this.options.maxListeners);
  54. Gaze.super_.prototype.setMaxListeners(this.options.maxListeners);
  55. delete this.options.maxListeners;
  56. }
  57. // Initialize the watch on files
  58. if (patterns) {
  59. this.add(patterns, done);
  60. }
  61. // keep the process alive
  62. this._keepalive = setInterval(function() {}, 200);
  63. return this;
  64. }
  65. util.inherits(Gaze, EE);
  66. // Main entry point. Start watching and call done when setup
  67. module.exports = function gaze(patterns, opts, done) {
  68. return new Gaze(patterns, opts, done);
  69. };
  70. module.exports.Gaze = Gaze;
  71. // Override the emit function to emit `all` events
  72. // and debounce on duplicate events per file
  73. Gaze.prototype.emit = function() {
  74. var self = this;
  75. var args = arguments;
  76. var e = args[0];
  77. var filepath = args[1];
  78. var timeoutId;
  79. // If not added/deleted/changed/renamed then just emit the event
  80. if (e.slice(-2) !== 'ed') {
  81. Gaze.super_.prototype.emit.apply(self, args);
  82. return this;
  83. }
  84. // Detect rename event, if added and previous deleted is in the cache
  85. if (e === 'added') {
  86. Object.keys(this._cached).forEach(function(oldFile) {
  87. if (self._cached[oldFile].indexOf('deleted') !== -1) {
  88. args[0] = e = 'renamed';
  89. [].push.call(args, oldFile);
  90. delete self._cached[oldFile];
  91. return false;
  92. }
  93. });
  94. }
  95. // If cached doesnt exist, create a delay before running the next
  96. // then emit the event
  97. var cache = this._cached[filepath] || [];
  98. if (cache.indexOf(e) === -1) {
  99. helper.objectPush(self._cached, filepath, e);
  100. clearTimeout(timeoutId);
  101. timeoutId = setTimeout(function() {
  102. delete self._cached[filepath];
  103. }, this.options.debounceDelay);
  104. // Emit the event and `all` event
  105. Gaze.super_.prototype.emit.apply(self, args);
  106. Gaze.super_.prototype.emit.apply(self, ['all', e].concat([].slice.call(args, 1)));
  107. }
  108. // Detect if new folder added to trigger for matching files within folder
  109. if (e === 'added') {
  110. if (helper.isDir(filepath)) {
  111. fs.readdirSync(filepath).map(function(file) {
  112. return path.join(filepath, file);
  113. }).filter(function(file) {
  114. return globule.isMatch(self._patterns, file, self.options);
  115. }).forEach(function(file) {
  116. self.emit('added', file);
  117. });
  118. }
  119. }
  120. return this;
  121. };
  122. // Close watchers
  123. Gaze.prototype.close = function(_reset) {
  124. var self = this;
  125. _reset = _reset === false ? false : true;
  126. Object.keys(self._watchers).forEach(function(file) {
  127. self._watchers[file].close();
  128. });
  129. self._watchers = Object.create(null);
  130. Object.keys(this._watched).forEach(function(dir) {
  131. self._unpollDir(dir);
  132. });
  133. if (_reset) {
  134. self._watched = Object.create(null);
  135. setTimeout(function() {
  136. self.emit('end');
  137. self.removeAllListeners();
  138. clearInterval(self._keepalive);
  139. }, delay + 100);
  140. }
  141. return self;
  142. };
  143. // Add file patterns to be watched
  144. Gaze.prototype.add = function(files, done) {
  145. if (typeof files === 'string') { files = [files]; }
  146. this._patterns = helper.unique.apply(null, [this._patterns, files]);
  147. files = globule.find(this._patterns, this.options);
  148. this._addToWatched(files);
  149. this.close(false);
  150. this._initWatched(done);
  151. };
  152. // Dont increment patterns and dont call done if nothing added
  153. Gaze.prototype._internalAdd = function(file, done) {
  154. var files = [];
  155. if (helper.isDir(file)) {
  156. files = [helper.markDir(file)].concat(globule.find(this._patterns, this.options));
  157. } else {
  158. if (globule.isMatch(this._patterns, file, this.options)) {
  159. files = [file];
  160. }
  161. }
  162. if (files.length > 0) {
  163. this._addToWatched(files);
  164. this.close(false);
  165. this._initWatched(done);
  166. }
  167. };
  168. // Remove file/dir from `watched`
  169. Gaze.prototype.remove = function(file) {
  170. var self = this;
  171. if (this._watched[file]) {
  172. // is dir, remove all files
  173. this._unpollDir(file);
  174. delete this._watched[file];
  175. } else {
  176. // is a file, find and remove
  177. Object.keys(this._watched).forEach(function(dir) {
  178. var index = self._watched[dir].indexOf(file);
  179. if (index !== -1) {
  180. self._unpollFile(file);
  181. self._watched[dir].splice(index, 1);
  182. return false;
  183. }
  184. });
  185. }
  186. if (this._watchers[file]) {
  187. this._watchers[file].close();
  188. }
  189. return this;
  190. };
  191. // Return watched files
  192. Gaze.prototype.watched = function() {
  193. return this._watched;
  194. };
  195. // Returns `watched` files with relative paths to process.cwd()
  196. Gaze.prototype.relative = function(dir, unixify) {
  197. var self = this;
  198. var relative = Object.create(null);
  199. var relDir, relFile, unixRelDir;
  200. var cwd = this.options.cwd || process.cwd();
  201. if (dir === '') { dir = '.'; }
  202. dir = helper.markDir(dir);
  203. unixify = unixify || false;
  204. Object.keys(this._watched).forEach(function(dir) {
  205. relDir = path.relative(cwd, dir) + path.sep;
  206. if (relDir === path.sep) { relDir = '.'; }
  207. unixRelDir = unixify ? helper.unixifyPathSep(relDir) : relDir;
  208. relative[unixRelDir] = self._watched[dir].map(function(file) {
  209. relFile = path.relative(path.join(cwd, relDir) || '', file || '');
  210. if (helper.isDir(file)) {
  211. relFile = helper.markDir(relFile);
  212. }
  213. if (unixify) {
  214. relFile = helper.unixifyPathSep(relFile);
  215. }
  216. return relFile;
  217. });
  218. });
  219. if (dir && unixify) {
  220. dir = helper.unixifyPathSep(dir);
  221. }
  222. return dir ? relative[dir] || [] : relative;
  223. };
  224. // Adds files and dirs to watched
  225. Gaze.prototype._addToWatched = function(files) {
  226. for (var i = 0; i < files.length; i++) {
  227. var file = files[i];
  228. var filepath = path.resolve(this.options.cwd, file);
  229. var dirname = (helper.isDir(file)) ? filepath : path.dirname(filepath);
  230. dirname = helper.markDir(dirname);
  231. // If a new dir is added
  232. if (helper.isDir(file) && !(filepath in this._watched)) {
  233. helper.objectPush(this._watched, filepath, []);
  234. }
  235. if (file.slice(-1) === '/') { filepath += path.sep; }
  236. helper.objectPush(this._watched, path.dirname(filepath) + path.sep, filepath);
  237. // add folders into the mix
  238. var readdir = fs.readdirSync(dirname);
  239. for (var j = 0; j < readdir.length; j++) {
  240. var dirfile = path.join(dirname, readdir[j]);
  241. if (fs.lstatSync(dirfile).isDirectory()) {
  242. helper.objectPush(this._watched, dirname, dirfile + path.sep);
  243. }
  244. }
  245. }
  246. return this;
  247. };
  248. Gaze.prototype._watchDir = function(dir, done) {
  249. var self = this;
  250. var timeoutId;
  251. try {
  252. this._watchers[dir] = fs.watch(dir, function(event) {
  253. // race condition. Let's give the fs a little time to settle down. so we
  254. // don't fire events on non existent files.
  255. clearTimeout(timeoutId);
  256. timeoutId = setTimeout(function() {
  257. // race condition. Ensure that this directory is still being watched
  258. // before continuing.
  259. if ((dir in self._watchers) && fs.existsSync(dir)) {
  260. done(null, dir);
  261. }
  262. }, delay + 100);
  263. });
  264. } catch (err) {
  265. return this._handleError(err);
  266. }
  267. return this;
  268. };
  269. Gaze.prototype._unpollFile = function(file) {
  270. if (this._pollers[file]) {
  271. fs.unwatchFile(file, this._pollers[file] );
  272. delete this._pollers[file];
  273. }
  274. return this;
  275. };
  276. Gaze.prototype._unpollDir = function(dir) {
  277. this._unpollFile(dir);
  278. for (var i = 0; i < this._watched[dir].length; i++) {
  279. this._unpollFile(this._watched[dir][i]);
  280. }
  281. };
  282. Gaze.prototype._pollFile = function(file, done) {
  283. var opts = { persistent: true, interval: this.options.interval };
  284. if (!this._pollers[file]) {
  285. this._pollers[file] = function(curr, prev) {
  286. done(null, file);
  287. };
  288. try {
  289. fs.watchFile(file, opts, this._pollers[file]);
  290. } catch (err) {
  291. return this._handleError(err);
  292. }
  293. }
  294. return this;
  295. };
  296. // Initialize the actual watch on `watched` files
  297. Gaze.prototype._initWatched = function(done) {
  298. var self = this;
  299. var cwd = this.options.cwd || process.cwd();
  300. var curWatched = Object.keys(self._watched);
  301. // if no matching files
  302. if (curWatched.length < 1) {
  303. // Defer to emitting to give a chance to attach event handlers.
  304. setImmediate(function () {
  305. self.emit('ready', self);
  306. if (done) { done.call(self, null, self); }
  307. self.emit('nomatch');
  308. });
  309. return;
  310. }
  311. helper.forEachSeries(curWatched, function(dir, next) {
  312. dir = dir || '';
  313. var files = self._watched[dir];
  314. // Triggered when a watched dir has an event
  315. self._watchDir(dir, function(event, dirpath) {
  316. var relDir = cwd === dir ? '.' : path.relative(cwd, dir);
  317. relDir = relDir || '';
  318. fs.readdir(dirpath, function(err, current) {
  319. if (err) { return self.emit('error', err); }
  320. if (!current) { return; }
  321. try {
  322. // append path.sep to directories so they match previous.
  323. current = current.map(function(curPath) {
  324. if (fs.existsSync(path.join(dir, curPath)) && fs.lstatSync(path.join(dir, curPath)).isDirectory()) {
  325. return curPath + path.sep;
  326. } else {
  327. return curPath;
  328. }
  329. });
  330. } catch (err) {
  331. // race condition-- sometimes the file no longer exists
  332. }
  333. // Get watched files for this dir
  334. var previous = self.relative(relDir);
  335. // If file was deleted
  336. previous.filter(function(file) {
  337. return current.indexOf(file) < 0;
  338. }).forEach(function(file) {
  339. if (!helper.isDir(file)) {
  340. var filepath = path.join(dir, file);
  341. self.remove(filepath);
  342. self.emit('deleted', filepath);
  343. }
  344. });
  345. // If file was added
  346. current.filter(function(file) {
  347. return previous.indexOf(file) < 0;
  348. }).forEach(function(file) {
  349. // Is it a matching pattern?
  350. var relFile = path.join(relDir, file);
  351. // Add to watch then emit event
  352. self._internalAdd(relFile, function() {
  353. self.emit('added', path.join(dir, file));
  354. });
  355. });
  356. });
  357. });
  358. // Watch for change/rename events on files
  359. files.forEach(function(file) {
  360. if (helper.isDir(file)) { return; }
  361. self._pollFile(file, function(err, filepath) {
  362. // Only emit changed if the file still exists
  363. // Prevents changed/deleted duplicate events
  364. if (fs.existsSync(filepath)) {
  365. self.emit('changed', filepath);
  366. }
  367. });
  368. });
  369. next();
  370. }, function() {
  371. // Return this instance of Gaze
  372. // delay before ready solves a lot of issues
  373. setTimeout(function() {
  374. self.emit('ready', self);
  375. if (done) { done.call(self, null, self); }
  376. }, delay + 100);
  377. });
  378. };
  379. // If an error, handle it here
  380. Gaze.prototype._handleError = function(err) {
  381. if (err.code === 'EMFILE') {
  382. return this.emit('error', new Error('EMFILE: Too many opened files.'));
  383. }
  384. return this.emit('error', err);
  385. };