You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. 'use strict';
  2. var EventEmitter = require('events').EventEmitter;
  3. var fs = require('fs');
  4. var sysPath = require('path');
  5. var asyncEach = require('async-each');
  6. var anymatch = require('anymatch');
  7. var globParent = require('glob-parent');
  8. var isGlob = require('is-glob');
  9. var isAbsolute = require('path-is-absolute');
  10. var inherits = require('inherits');
  11. var braces = require('braces');
  12. var normalizePath = require('normalize-path');
  13. var upath = require('upath');
  14. var NodeFsHandler = require('./lib/nodefs-handler');
  15. var FsEventsHandler = require('./lib/fsevents-handler');
  16. var arrify = function(value) {
  17. if (value == null) return [];
  18. return Array.isArray(value) ? value : [value];
  19. };
  20. var flatten = function(list, result) {
  21. if (result == null) result = [];
  22. list.forEach(function(item) {
  23. if (Array.isArray(item)) {
  24. flatten(item, result);
  25. } else {
  26. result.push(item);
  27. }
  28. });
  29. return result;
  30. };
  31. // Little isString util for use in Array#every.
  32. var isString = function(thing) {
  33. return typeof thing === 'string';
  34. };
  35. // Public: Main class.
  36. // Watches files & directories for changes.
  37. //
  38. // * _opts - object, chokidar options hash
  39. //
  40. // Emitted events:
  41. // `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  42. //
  43. // Examples
  44. //
  45. // var watcher = new FSWatcher()
  46. // .add(directories)
  47. // .on('add', path => console.log('File', path, 'was added'))
  48. // .on('change', path => console.log('File', path, 'was changed'))
  49. // .on('unlink', path => console.log('File', path, 'was removed'))
  50. // .on('all', (event, path) => console.log(path, ' emitted ', event))
  51. //
  52. function FSWatcher(_opts) {
  53. EventEmitter.call(this);
  54. var opts = {};
  55. // in case _opts that is passed in is a frozen object
  56. if (_opts) for (var opt in _opts) opts[opt] = _opts[opt];
  57. this._watched = Object.create(null);
  58. this._closers = Object.create(null);
  59. this._ignoredPaths = Object.create(null);
  60. Object.defineProperty(this, '_globIgnored', {
  61. get: function() { return Object.keys(this._ignoredPaths); }
  62. });
  63. this.closed = false;
  64. this._throttled = Object.create(null);
  65. this._symlinkPaths = Object.create(null);
  66. function undef(key) {
  67. return opts[key] === undefined;
  68. }
  69. // Set up default options.
  70. if (undef('persistent')) opts.persistent = true;
  71. if (undef('ignoreInitial')) opts.ignoreInitial = false;
  72. if (undef('ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  73. if (undef('interval')) opts.interval = 100;
  74. if (undef('binaryInterval')) opts.binaryInterval = 300;
  75. if (undef('disableGlobbing')) opts.disableGlobbing = false;
  76. this.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  77. // Enable fsevents on OS X when polling isn't explicitly enabled.
  78. if (undef('useFsEvents')) opts.useFsEvents = !opts.usePolling;
  79. // If we can't use fsevents, ensure the options reflect it's disabled.
  80. if (!FsEventsHandler.canUse()) opts.useFsEvents = false;
  81. // Use polling on Mac if not using fsevents.
  82. // Other platforms use non-polling fs.watch.
  83. if (undef('usePolling') && !opts.useFsEvents) {
  84. opts.usePolling = process.platform === 'darwin';
  85. }
  86. // Global override (useful for end-developers that need to force polling for all
  87. // instances of chokidar, regardless of usage/dependency depth)
  88. var envPoll = process.env.CHOKIDAR_USEPOLLING;
  89. if (envPoll !== undefined) {
  90. var envLower = envPoll.toLowerCase();
  91. if (envLower === 'false' || envLower === '0') {
  92. opts.usePolling = false;
  93. } else if (envLower === 'true' || envLower === '1') {
  94. opts.usePolling = true;
  95. } else {
  96. opts.usePolling = !!envLower
  97. }
  98. }
  99. var envInterval = process.env.CHOKIDAR_INTERVAL;
  100. if (envInterval) {
  101. opts.interval = parseInt(envInterval);
  102. }
  103. // Editor atomic write normalization enabled by default with fs.watch
  104. if (undef('atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  105. if (opts.atomic) this._pendingUnlinks = Object.create(null);
  106. if (undef('followSymlinks')) opts.followSymlinks = true;
  107. if (undef('awaitWriteFinish')) opts.awaitWriteFinish = false;
  108. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  109. var awf = opts.awaitWriteFinish;
  110. if (awf) {
  111. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  112. if (!awf.pollInterval) awf.pollInterval = 100;
  113. this._pendingWrites = Object.create(null);
  114. }
  115. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  116. this._isntIgnored = function(path, stat) {
  117. return !this._isIgnored(path, stat);
  118. }.bind(this);
  119. var readyCalls = 0;
  120. this._emitReady = function() {
  121. if (++readyCalls >= this._readyCount) {
  122. this._emitReady = Function.prototype;
  123. this._readyEmitted = true;
  124. // use process.nextTick to allow time for listener to be bound
  125. process.nextTick(this.emit.bind(this, 'ready'));
  126. }
  127. }.bind(this);
  128. this.options = opts;
  129. // You’re frozen when your heart’s not open.
  130. Object.freeze(opts);
  131. }
  132. inherits(FSWatcher, EventEmitter);
  133. // Common helpers
  134. // --------------
  135. // Private method: Normalize and emit events
  136. //
  137. // * event - string, type of event
  138. // * path - string, file or directory path
  139. // * val[1..3] - arguments to be passed with event
  140. //
  141. // Returns the error if defined, otherwise the value of the
  142. // FSWatcher instance's `closed` flag
  143. FSWatcher.prototype._emit = function(event, path, val1, val2, val3) {
  144. if (this.options.cwd) path = sysPath.relative(this.options.cwd, path);
  145. var args = [event, path];
  146. if (val3 !== undefined) args.push(val1, val2, val3);
  147. else if (val2 !== undefined) args.push(val1, val2);
  148. else if (val1 !== undefined) args.push(val1);
  149. var awf = this.options.awaitWriteFinish;
  150. if (awf && this._pendingWrites[path]) {
  151. this._pendingWrites[path].lastChange = new Date();
  152. return this;
  153. }
  154. if (this.options.atomic) {
  155. if (event === 'unlink') {
  156. this._pendingUnlinks[path] = args;
  157. setTimeout(function() {
  158. Object.keys(this._pendingUnlinks).forEach(function(path) {
  159. this.emit.apply(this, this._pendingUnlinks[path]);
  160. this.emit.apply(this, ['all'].concat(this._pendingUnlinks[path]));
  161. delete this._pendingUnlinks[path];
  162. }.bind(this));
  163. }.bind(this), typeof this.options.atomic === "number"
  164. ? this.options.atomic
  165. : 100);
  166. return this;
  167. } else if (event === 'add' && this._pendingUnlinks[path]) {
  168. event = args[0] = 'change';
  169. delete this._pendingUnlinks[path];
  170. }
  171. }
  172. var emitEvent = function() {
  173. this.emit.apply(this, args);
  174. if (event !== 'error') this.emit.apply(this, ['all'].concat(args));
  175. }.bind(this);
  176. if (awf && (event === 'add' || event === 'change') && this._readyEmitted) {
  177. var awfEmit = function(err, stats) {
  178. if (err) {
  179. event = args[0] = 'error';
  180. args[1] = err;
  181. emitEvent();
  182. } else if (stats) {
  183. // if stats doesn't exist the file must have been deleted
  184. if (args.length > 2) {
  185. args[2] = stats;
  186. } else {
  187. args.push(stats);
  188. }
  189. emitEvent();
  190. }
  191. };
  192. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  193. return this;
  194. }
  195. if (event === 'change') {
  196. if (!this._throttle('change', path, 50)) return this;
  197. }
  198. if (
  199. this.options.alwaysStat && val1 === undefined &&
  200. (event === 'add' || event === 'addDir' || event === 'change')
  201. ) {
  202. var fullPath = this.options.cwd ? sysPath.join(this.options.cwd, path) : path;
  203. fs.stat(fullPath, function(error, stats) {
  204. // Suppress event when fs.stat fails, to avoid sending undefined 'stat'
  205. if (error || !stats) return;
  206. args.push(stats);
  207. emitEvent();
  208. });
  209. } else {
  210. emitEvent();
  211. }
  212. return this;
  213. };
  214. // Private method: Common handler for errors
  215. //
  216. // * error - object, Error instance
  217. //
  218. // Returns the error if defined, otherwise the value of the
  219. // FSWatcher instance's `closed` flag
  220. FSWatcher.prototype._handleError = function(error) {
  221. var code = error && error.code;
  222. var ipe = this.options.ignorePermissionErrors;
  223. if (error &&
  224. code !== 'ENOENT' &&
  225. code !== 'ENOTDIR' &&
  226. (!ipe || (code !== 'EPERM' && code !== 'EACCES'))
  227. ) this.emit('error', error);
  228. return error || this.closed;
  229. };
  230. // Private method: Helper utility for throttling
  231. //
  232. // * action - string, type of action being throttled
  233. // * path - string, path being acted upon
  234. // * timeout - int, duration of time to suppress duplicate actions
  235. //
  236. // Returns throttle tracking object or false if action should be suppressed
  237. FSWatcher.prototype._throttle = function(action, path, timeout) {
  238. if (!(action in this._throttled)) {
  239. this._throttled[action] = Object.create(null);
  240. }
  241. var throttled = this._throttled[action];
  242. if (path in throttled) {
  243. throttled[path].count++;
  244. return false;
  245. }
  246. function clear() {
  247. var count = throttled[path] ? throttled[path].count : 0;
  248. delete throttled[path];
  249. clearTimeout(timeoutObject);
  250. return count;
  251. }
  252. var timeoutObject = setTimeout(clear, timeout);
  253. throttled[path] = {timeoutObject: timeoutObject, clear: clear, count: 0};
  254. return throttled[path];
  255. };
  256. // Private method: Awaits write operation to finish
  257. //
  258. // * path - string, path being acted upon
  259. // * threshold - int, time in milliseconds a file size must be fixed before
  260. // acknowledging write operation is finished
  261. // * awfEmit - function, to be called when ready for event to be emitted
  262. // Polls a newly created file for size variations. When files size does not
  263. // change for 'threshold' milliseconds calls callback.
  264. FSWatcher.prototype._awaitWriteFinish = function(path, threshold, event, awfEmit) {
  265. var timeoutHandler;
  266. var fullPath = path;
  267. if (this.options.cwd && !isAbsolute(path)) {
  268. fullPath = sysPath.join(this.options.cwd, path);
  269. }
  270. var now = new Date();
  271. var awaitWriteFinish = (function (prevStat) {
  272. fs.stat(fullPath, function(err, curStat) {
  273. if (err || !(path in this._pendingWrites)) {
  274. if (err && err.code !== 'ENOENT') awfEmit(err);
  275. return;
  276. }
  277. var now = new Date();
  278. if (prevStat && curStat.size != prevStat.size) {
  279. this._pendingWrites[path].lastChange = now;
  280. }
  281. if (now - this._pendingWrites[path].lastChange >= threshold) {
  282. delete this._pendingWrites[path];
  283. awfEmit(null, curStat);
  284. } else {
  285. timeoutHandler = setTimeout(
  286. awaitWriteFinish.bind(this, curStat),
  287. this.options.awaitWriteFinish.pollInterval
  288. );
  289. }
  290. }.bind(this));
  291. }.bind(this));
  292. if (!(path in this._pendingWrites)) {
  293. this._pendingWrites[path] = {
  294. lastChange: now,
  295. cancelWait: function() {
  296. delete this._pendingWrites[path];
  297. clearTimeout(timeoutHandler);
  298. return event;
  299. }.bind(this)
  300. };
  301. timeoutHandler = setTimeout(
  302. awaitWriteFinish.bind(this),
  303. this.options.awaitWriteFinish.pollInterval
  304. );
  305. }
  306. };
  307. // Private method: Determines whether user has asked to ignore this path
  308. //
  309. // * path - string, path to file or directory
  310. // * stats - object, result of fs.stat
  311. //
  312. // Returns boolean
  313. var dotRe = /\..*\.(sw[px])$|\~$|\.subl.*\.tmp/;
  314. FSWatcher.prototype._isIgnored = function(path, stats) {
  315. if (this.options.atomic && dotRe.test(path)) return true;
  316. if (!this._userIgnored) {
  317. var cwd = this.options.cwd;
  318. var ignored = this.options.ignored;
  319. if (cwd && ignored) {
  320. ignored = ignored.map(function (path) {
  321. if (typeof path !== 'string') return path;
  322. return upath.normalize(isAbsolute(path) ? path : sysPath.join(cwd, path));
  323. });
  324. }
  325. var paths = arrify(ignored)
  326. .filter(function(path) {
  327. return typeof path === 'string' && !isGlob(path);
  328. }).map(function(path) {
  329. return path + '/**';
  330. });
  331. this._userIgnored = anymatch(
  332. this._globIgnored.concat(ignored).concat(paths)
  333. );
  334. }
  335. return this._userIgnored([path, stats]);
  336. };
  337. // Private method: Provides a set of common helpers and properties relating to
  338. // symlink and glob handling
  339. //
  340. // * path - string, file, directory, or glob pattern being watched
  341. // * depth - int, at any depth > 0, this isn't a glob
  342. //
  343. // Returns object containing helpers for this path
  344. var replacerRe = /^\.[\/\\]/;
  345. FSWatcher.prototype._getWatchHelpers = function(path, depth) {
  346. path = path.replace(replacerRe, '');
  347. var watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  348. var fullWatchPath = sysPath.resolve(watchPath);
  349. var hasGlob = watchPath !== path;
  350. var globFilter = hasGlob ? anymatch(path) : false;
  351. var follow = this.options.followSymlinks;
  352. var globSymlink = hasGlob && follow ? null : false;
  353. var checkGlobSymlink = function(entry) {
  354. // only need to resolve once
  355. // first entry should always have entry.parentDir === ''
  356. if (globSymlink == null) {
  357. globSymlink = entry.fullParentDir === fullWatchPath ? false : {
  358. realPath: entry.fullParentDir,
  359. linkPath: fullWatchPath
  360. };
  361. }
  362. if (globSymlink) {
  363. return entry.fullPath.replace(globSymlink.realPath, globSymlink.linkPath);
  364. }
  365. return entry.fullPath;
  366. };
  367. var entryPath = function(entry) {
  368. return sysPath.join(watchPath,
  369. sysPath.relative(watchPath, checkGlobSymlink(entry))
  370. );
  371. };
  372. var filterPath = function(entry) {
  373. if (entry.stat && entry.stat.isSymbolicLink()) return filterDir(entry);
  374. var resolvedPath = entryPath(entry);
  375. return (!hasGlob || globFilter(resolvedPath)) &&
  376. this._isntIgnored(resolvedPath, entry.stat) &&
  377. (this.options.ignorePermissionErrors ||
  378. this._hasReadPermissions(entry.stat));
  379. }.bind(this);
  380. var getDirParts = function(path) {
  381. if (!hasGlob) return false;
  382. var parts = [];
  383. var expandedPath = braces.expand(path);
  384. expandedPath.forEach(function(path) {
  385. parts.push(sysPath.relative(watchPath, path).split(/[\/\\]/));
  386. });
  387. return parts;
  388. };
  389. var dirParts = getDirParts(path);
  390. if (dirParts) {
  391. dirParts.forEach(function(parts) {
  392. if (parts.length > 1) parts.pop();
  393. });
  394. }
  395. var unmatchedGlob;
  396. var filterDir = function(entry) {
  397. if (hasGlob) {
  398. var entryParts = getDirParts(checkGlobSymlink(entry));
  399. var globstar = false;
  400. unmatchedGlob = !dirParts.some(function(parts) {
  401. return parts.every(function(part, i) {
  402. if (part === '**') globstar = true;
  403. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i]);
  404. });
  405. });
  406. }
  407. return !unmatchedGlob && this._isntIgnored(entryPath(entry), entry.stat);
  408. }.bind(this);
  409. return {
  410. followSymlinks: follow,
  411. statMethod: follow ? 'stat' : 'lstat',
  412. path: path,
  413. watchPath: watchPath,
  414. entryPath: entryPath,
  415. hasGlob: hasGlob,
  416. globFilter: globFilter,
  417. filterPath: filterPath,
  418. filterDir: filterDir
  419. };
  420. };
  421. // Directory helpers
  422. // -----------------
  423. // Private method: Provides directory tracking objects
  424. //
  425. // * directory - string, path of the directory
  426. //
  427. // Returns the directory's tracking object
  428. FSWatcher.prototype._getWatchedDir = function(directory) {
  429. var dir = sysPath.resolve(directory);
  430. var watcherRemove = this._remove.bind(this);
  431. if (!(dir in this._watched)) this._watched[dir] = {
  432. _items: Object.create(null),
  433. add: function(item) {
  434. if (item !== '.' && item !== '..') this._items[item] = true;
  435. },
  436. remove: function(item) {
  437. delete this._items[item];
  438. if (!this.children().length) {
  439. fs.readdir(dir, function(err) {
  440. if (err) watcherRemove(sysPath.dirname(dir), sysPath.basename(dir));
  441. });
  442. }
  443. },
  444. has: function(item) {return item in this._items;},
  445. children: function() {return Object.keys(this._items);}
  446. };
  447. return this._watched[dir];
  448. };
  449. // File helpers
  450. // ------------
  451. // Private method: Check for read permissions
  452. // Based on this answer on SO: http://stackoverflow.com/a/11781404/1358405
  453. //
  454. // * stats - object, result of fs.stat
  455. //
  456. // Returns boolean
  457. FSWatcher.prototype._hasReadPermissions = function(stats) {
  458. return Boolean(4 & parseInt(((stats && stats.mode) & 0x1ff).toString(8)[0], 10));
  459. };
  460. // Private method: Handles emitting unlink events for
  461. // files and directories, and via recursion, for
  462. // files and directories within directories that are unlinked
  463. //
  464. // * directory - string, directory within which the following item is located
  465. // * item - string, base path of item/directory
  466. //
  467. // Returns nothing
  468. FSWatcher.prototype._remove = function(directory, item) {
  469. // if what is being deleted is a directory, get that directory's paths
  470. // for recursive deleting and cleaning of watched object
  471. // if it is not a directory, nestedDirectoryChildren will be empty array
  472. var path = sysPath.join(directory, item);
  473. var fullPath = sysPath.resolve(path);
  474. var isDirectory = this._watched[path] || this._watched[fullPath];
  475. // prevent duplicate handling in case of arriving here nearly simultaneously
  476. // via multiple paths (such as _handleFile and _handleDir)
  477. if (!this._throttle('remove', path, 100)) return;
  478. // if the only watched file is removed, watch for its return
  479. var watchedDirs = Object.keys(this._watched);
  480. if (!isDirectory && !this.options.useFsEvents && watchedDirs.length === 1) {
  481. this.add(directory, item, true);
  482. }
  483. // This will create a new entry in the watched object in either case
  484. // so we got to do the directory check beforehand
  485. var nestedDirectoryChildren = this._getWatchedDir(path).children();
  486. // Recursively remove children directories / files.
  487. nestedDirectoryChildren.forEach(function(nestedItem) {
  488. this._remove(path, nestedItem);
  489. }, this);
  490. // Check if item was on the watched list and remove it
  491. var parent = this._getWatchedDir(directory);
  492. var wasTracked = parent.has(item);
  493. parent.remove(item);
  494. // If we wait for this file to be fully written, cancel the wait.
  495. var relPath = path;
  496. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  497. if (this.options.awaitWriteFinish && this._pendingWrites[relPath]) {
  498. var event = this._pendingWrites[relPath].cancelWait();
  499. if (event === 'add') return;
  500. }
  501. // The Entry will either be a directory that just got removed
  502. // or a bogus entry to a file, in either case we have to remove it
  503. delete this._watched[path];
  504. delete this._watched[fullPath];
  505. var eventName = isDirectory ? 'unlinkDir' : 'unlink';
  506. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  507. // Avoid conflicts if we later create another file with the same name
  508. if (!this.options.useFsEvents) {
  509. this._closePath(path);
  510. }
  511. };
  512. FSWatcher.prototype._closePath = function(path) {
  513. if (!this._closers[path]) return;
  514. this._closers[path].forEach(function(closer) {
  515. closer();
  516. });
  517. delete this._closers[path];
  518. this._getWatchedDir(sysPath.dirname(path)).remove(sysPath.basename(path));
  519. }
  520. // Public method: Adds paths to be watched on an existing FSWatcher instance
  521. // * paths - string or array of strings, file/directory paths and/or globs
  522. // * _origAdd - private boolean, for handling non-existent paths to be watched
  523. // * _internal - private boolean, indicates a non-user add
  524. // Returns an instance of FSWatcher for chaining.
  525. FSWatcher.prototype.add = function(paths, _origAdd, _internal) {
  526. var disableGlobbing = this.options.disableGlobbing;
  527. var cwd = this.options.cwd;
  528. this.closed = false;
  529. paths = flatten(arrify(paths));
  530. if (!paths.every(isString)) {
  531. throw new TypeError('Non-string provided as watch path: ' + paths);
  532. }
  533. if (cwd) paths = paths.map(function(path) {
  534. var absPath;
  535. if (isAbsolute(path)) {
  536. absPath = path;
  537. } else if (path[0] === '!') {
  538. absPath = '!' + sysPath.join(cwd, path.substring(1));
  539. } else {
  540. absPath = sysPath.join(cwd, path);
  541. }
  542. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  543. if (disableGlobbing || !isGlob(path)) {
  544. return absPath;
  545. } else {
  546. return normalizePath(absPath);
  547. }
  548. });
  549. // set aside negated glob strings
  550. paths = paths.filter(function(path) {
  551. if (path[0] === '!') {
  552. this._ignoredPaths[path.substring(1)] = true;
  553. } else {
  554. // if a path is being added that was previously ignored, stop ignoring it
  555. delete this._ignoredPaths[path];
  556. delete this._ignoredPaths[path + '/**'];
  557. // reset the cached userIgnored anymatch fn
  558. // to make ignoredPaths changes effective
  559. this._userIgnored = null;
  560. return true;
  561. }
  562. }, this);
  563. if (this.options.useFsEvents && FsEventsHandler.canUse()) {
  564. if (!this._readyCount) this._readyCount = paths.length;
  565. if (this.options.persistent) this._readyCount *= 2;
  566. paths.forEach(this._addToFsEvents, this);
  567. } else {
  568. if (!this._readyCount) this._readyCount = 0;
  569. this._readyCount += paths.length;
  570. asyncEach(paths, function(path, next) {
  571. this._addToNodeFs(path, !_internal, 0, 0, _origAdd, function(err, res) {
  572. if (res) this._emitReady();
  573. next(err, res);
  574. }.bind(this));
  575. }.bind(this), function(error, results) {
  576. results.forEach(function(item) {
  577. if (!item || this.closed) return;
  578. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  579. }, this);
  580. }.bind(this));
  581. }
  582. return this;
  583. };
  584. // Public method: Close watchers or start ignoring events from specified paths.
  585. // * paths - string or array of strings, file/directory paths and/or globs
  586. // Returns instance of FSWatcher for chaining.
  587. FSWatcher.prototype.unwatch = function(paths) {
  588. if (this.closed) return this;
  589. paths = flatten(arrify(paths));
  590. paths.forEach(function(path) {
  591. // convert to absolute path unless relative path already matches
  592. if (!isAbsolute(path) && !this._closers[path]) {
  593. if (this.options.cwd) path = sysPath.join(this.options.cwd, path);
  594. path = sysPath.resolve(path);
  595. }
  596. this._closePath(path);
  597. this._ignoredPaths[path] = true;
  598. if (path in this._watched) {
  599. this._ignoredPaths[path + '/**'] = true;
  600. }
  601. // reset the cached userIgnored anymatch fn
  602. // to make ignoredPaths changes effective
  603. this._userIgnored = null;
  604. }, this);
  605. return this;
  606. };
  607. // Public method: Close watchers and remove all listeners from watched paths.
  608. // Returns instance of FSWatcher for chaining.
  609. FSWatcher.prototype.close = function() {
  610. if (this.closed) return this;
  611. this.closed = true;
  612. Object.keys(this._closers).forEach(function(watchPath) {
  613. this._closers[watchPath].forEach(function(closer) {
  614. closer();
  615. });
  616. delete this._closers[watchPath];
  617. }, this);
  618. this._watched = Object.create(null);
  619. this.removeAllListeners();
  620. return this;
  621. };
  622. // Public method: Expose list of watched paths
  623. // Returns object w/ dir paths as keys and arrays of contained paths as values.
  624. FSWatcher.prototype.getWatched = function() {
  625. var watchList = {};
  626. Object.keys(this._watched).forEach(function(dir) {
  627. var key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  628. watchList[key || '.'] = Object.keys(this._watched[dir]._items).sort();
  629. }.bind(this));
  630. return watchList;
  631. };
  632. // Attach watch handler prototype methods
  633. function importHandler(handler) {
  634. Object.keys(handler.prototype).forEach(function(method) {
  635. FSWatcher.prototype[method] = handler.prototype[method];
  636. });
  637. }
  638. importHandler(NodeFsHandler);
  639. if (FsEventsHandler.canUse()) importHandler(FsEventsHandler);
  640. // Export FSWatcher class
  641. exports.FSWatcher = FSWatcher;
  642. // Public function: Instantiates watcher with paths to be tracked.
  643. // * paths - string or array of strings, file/directory paths and/or globs
  644. // * options - object, chokidar options
  645. // Returns an instance of FSWatcher for chaining.
  646. exports.watch = function(paths, options) {
  647. return new FSWatcher(options).add(paths);
  648. };