index.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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) return false;
  243. function clear() {
  244. delete throttled[path];
  245. clearTimeout(timeoutObject);
  246. }
  247. var timeoutObject = setTimeout(clear, timeout);
  248. throttled[path] = {timeoutObject: timeoutObject, clear: clear};
  249. return throttled[path];
  250. };
  251. // Private method: Awaits write operation to finish
  252. //
  253. // * path - string, path being acted upon
  254. // * threshold - int, time in milliseconds a file size must be fixed before
  255. // acknowledgeing write operation is finished
  256. // * awfEmit - function, to be called when ready for event to be emitted
  257. // Polls a newly created file for size variations. When files size does not
  258. // change for 'threshold' milliseconds calls callback.
  259. FSWatcher.prototype._awaitWriteFinish = function(path, threshold, event, awfEmit) {
  260. var timeoutHandler;
  261. var fullPath = path;
  262. if (this.options.cwd && !isAbsolute(path)) {
  263. fullPath = sysPath.join(this.options.cwd, path);
  264. }
  265. var now = new Date();
  266. var awaitWriteFinish = (function (prevStat) {
  267. fs.stat(fullPath, function(err, curStat) {
  268. if (err || !(path in this._pendingWrites)) {
  269. if (err && err.code !== 'ENOENT') awfEmit(err);
  270. return;
  271. }
  272. var now = new Date();
  273. if (prevStat && curStat.size != prevStat.size) {
  274. this._pendingWrites[path].lastChange = now;
  275. }
  276. if (now - this._pendingWrites[path].lastChange >= threshold) {
  277. delete this._pendingWrites[path];
  278. awfEmit(null, curStat);
  279. } else {
  280. timeoutHandler = setTimeout(
  281. awaitWriteFinish.bind(this, curStat),
  282. this.options.awaitWriteFinish.pollInterval
  283. );
  284. }
  285. }.bind(this));
  286. }.bind(this));
  287. if (!(path in this._pendingWrites)) {
  288. this._pendingWrites[path] = {
  289. lastChange: now,
  290. cancelWait: function() {
  291. delete this._pendingWrites[path];
  292. clearTimeout(timeoutHandler);
  293. return event;
  294. }.bind(this)
  295. };
  296. timeoutHandler = setTimeout(
  297. awaitWriteFinish.bind(this),
  298. this.options.awaitWriteFinish.pollInterval
  299. );
  300. }
  301. };
  302. // Private method: Determines whether user has asked to ignore this path
  303. //
  304. // * path - string, path to file or directory
  305. // * stats - object, result of fs.stat
  306. //
  307. // Returns boolean
  308. var dotRe = /\..*\.(sw[px])$|\~$|\.subl.*\.tmp/;
  309. FSWatcher.prototype._isIgnored = function(path, stats) {
  310. if (this.options.atomic && dotRe.test(path)) return true;
  311. if (!this._userIgnored) {
  312. var cwd = this.options.cwd;
  313. var ignored = this.options.ignored;
  314. if (cwd && ignored) {
  315. ignored = ignored.map(function (path) {
  316. if (typeof path !== 'string') return path;
  317. return upath.normalize(isAbsolute(path) ? path : sysPath.join(cwd, path));
  318. });
  319. }
  320. var paths = arrify(ignored)
  321. .filter(function(path) {
  322. return typeof path === 'string' && !isGlob(path);
  323. }).map(function(path) {
  324. return path + '/**';
  325. });
  326. this._userIgnored = anymatch(
  327. this._globIgnored.concat(ignored).concat(paths)
  328. );
  329. }
  330. return this._userIgnored([path, stats]);
  331. };
  332. // Private method: Provides a set of common helpers and properties relating to
  333. // symlink and glob handling
  334. //
  335. // * path - string, file, directory, or glob pattern being watched
  336. // * depth - int, at any depth > 0, this isn't a glob
  337. //
  338. // Returns object containing helpers for this path
  339. var replacerRe = /^\.[\/\\]/;
  340. FSWatcher.prototype._getWatchHelpers = function(path, depth) {
  341. path = path.replace(replacerRe, '');
  342. var watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  343. var fullWatchPath = sysPath.resolve(watchPath);
  344. var hasGlob = watchPath !== path;
  345. var globFilter = hasGlob ? anymatch(path) : false;
  346. var follow = this.options.followSymlinks;
  347. var globSymlink = hasGlob && follow ? null : false;
  348. var checkGlobSymlink = function(entry) {
  349. // only need to resolve once
  350. // first entry should always have entry.parentDir === ''
  351. if (globSymlink == null) {
  352. globSymlink = entry.fullParentDir === fullWatchPath ? false : {
  353. realPath: entry.fullParentDir,
  354. linkPath: fullWatchPath
  355. };
  356. }
  357. if (globSymlink) {
  358. return entry.fullPath.replace(globSymlink.realPath, globSymlink.linkPath);
  359. }
  360. return entry.fullPath;
  361. };
  362. var entryPath = function(entry) {
  363. return sysPath.join(watchPath,
  364. sysPath.relative(watchPath, checkGlobSymlink(entry))
  365. );
  366. };
  367. var filterPath = function(entry) {
  368. if (entry.stat && entry.stat.isSymbolicLink()) return filterDir(entry);
  369. var resolvedPath = entryPath(entry);
  370. return (!hasGlob || globFilter(resolvedPath)) &&
  371. this._isntIgnored(resolvedPath, entry.stat) &&
  372. (this.options.ignorePermissionErrors ||
  373. this._hasReadPermissions(entry.stat));
  374. }.bind(this);
  375. var getDirParts = function(path) {
  376. if (!hasGlob) return false;
  377. var parts = [];
  378. var expandedPath = braces.expand(path);
  379. expandedPath.forEach(function(path) {
  380. parts.push(sysPath.relative(watchPath, path).split(/[\/\\]/));
  381. });
  382. return parts;
  383. };
  384. var dirParts = getDirParts(path);
  385. if (dirParts) {
  386. dirParts.forEach(function(parts) {
  387. if (parts.length > 1) parts.pop();
  388. });
  389. }
  390. var unmatchedGlob;
  391. var filterDir = function(entry) {
  392. if (hasGlob) {
  393. var entryParts = getDirParts(checkGlobSymlink(entry));
  394. var globstar = false;
  395. unmatchedGlob = !dirParts.some(function(parts) {
  396. return parts.every(function(part, i) {
  397. if (part === '**') globstar = true;
  398. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i]);
  399. });
  400. });
  401. }
  402. return !unmatchedGlob && this._isntIgnored(entryPath(entry), entry.stat);
  403. }.bind(this);
  404. return {
  405. followSymlinks: follow,
  406. statMethod: follow ? 'stat' : 'lstat',
  407. path: path,
  408. watchPath: watchPath,
  409. entryPath: entryPath,
  410. hasGlob: hasGlob,
  411. globFilter: globFilter,
  412. filterPath: filterPath,
  413. filterDir: filterDir
  414. };
  415. };
  416. // Directory helpers
  417. // -----------------
  418. // Private method: Provides directory tracking objects
  419. //
  420. // * directory - string, path of the directory
  421. //
  422. // Returns the directory's tracking object
  423. FSWatcher.prototype._getWatchedDir = function(directory) {
  424. var dir = sysPath.resolve(directory);
  425. var watcherRemove = this._remove.bind(this);
  426. if (!(dir in this._watched)) this._watched[dir] = {
  427. _items: Object.create(null),
  428. add: function(item) {
  429. if (item !== '.' && item !== '..') this._items[item] = true;
  430. },
  431. remove: function(item) {
  432. delete this._items[item];
  433. if (!this.children().length) {
  434. fs.readdir(dir, function(err) {
  435. if (err) watcherRemove(sysPath.dirname(dir), sysPath.basename(dir));
  436. });
  437. }
  438. },
  439. has: function(item) {return item in this._items;},
  440. children: function() {return Object.keys(this._items);}
  441. };
  442. return this._watched[dir];
  443. };
  444. // File helpers
  445. // ------------
  446. // Private method: Check for read permissions
  447. // Based on this answer on SO: http://stackoverflow.com/a/11781404/1358405
  448. //
  449. // * stats - object, result of fs.stat
  450. //
  451. // Returns boolean
  452. FSWatcher.prototype._hasReadPermissions = function(stats) {
  453. return Boolean(4 & parseInt(((stats && stats.mode) & 0x1ff).toString(8)[0], 10));
  454. };
  455. // Private method: Handles emitting unlink events for
  456. // files and directories, and via recursion, for
  457. // files and directories within directories that are unlinked
  458. //
  459. // * directory - string, directory within which the following item is located
  460. // * item - string, base path of item/directory
  461. //
  462. // Returns nothing
  463. FSWatcher.prototype._remove = function(directory, item) {
  464. // if what is being deleted is a directory, get that directory's paths
  465. // for recursive deleting and cleaning of watched object
  466. // if it is not a directory, nestedDirectoryChildren will be empty array
  467. var path = sysPath.join(directory, item);
  468. var fullPath = sysPath.resolve(path);
  469. var isDirectory = this._watched[path] || this._watched[fullPath];
  470. // prevent duplicate handling in case of arriving here nearly simultaneously
  471. // via multiple paths (such as _handleFile and _handleDir)
  472. if (!this._throttle('remove', path, 100)) return;
  473. // if the only watched file is removed, watch for its return
  474. var watchedDirs = Object.keys(this._watched);
  475. if (!isDirectory && !this.options.useFsEvents && watchedDirs.length === 1) {
  476. this.add(directory, item, true);
  477. }
  478. // This will create a new entry in the watched object in either case
  479. // so we got to do the directory check beforehand
  480. var nestedDirectoryChildren = this._getWatchedDir(path).children();
  481. // Recursively remove children directories / files.
  482. nestedDirectoryChildren.forEach(function(nestedItem) {
  483. this._remove(path, nestedItem);
  484. }, this);
  485. // Check if item was on the watched list and remove it
  486. var parent = this._getWatchedDir(directory);
  487. var wasTracked = parent.has(item);
  488. parent.remove(item);
  489. // If we wait for this file to be fully written, cancel the wait.
  490. var relPath = path;
  491. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  492. if (this.options.awaitWriteFinish && this._pendingWrites[relPath]) {
  493. var event = this._pendingWrites[relPath].cancelWait();
  494. if (event === 'add') return;
  495. }
  496. // The Entry will either be a directory that just got removed
  497. // or a bogus entry to a file, in either case we have to remove it
  498. delete this._watched[path];
  499. delete this._watched[fullPath];
  500. var eventName = isDirectory ? 'unlinkDir' : 'unlink';
  501. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  502. // Avoid conflicts if we later create another file with the same name
  503. if (!this.options.useFsEvents) {
  504. this._closePath(path);
  505. }
  506. };
  507. FSWatcher.prototype._closePath = function(path) {
  508. if (!this._closers[path]) return;
  509. this._closers[path]();
  510. delete this._closers[path];
  511. this._getWatchedDir(sysPath.dirname(path)).remove(sysPath.basename(path));
  512. }
  513. // Public method: Adds paths to be watched on an existing FSWatcher instance
  514. // * paths - string or array of strings, file/directory paths and/or globs
  515. // * _origAdd - private boolean, for handling non-existent paths to be watched
  516. // * _internal - private boolean, indicates a non-user add
  517. // Returns an instance of FSWatcher for chaining.
  518. FSWatcher.prototype.add = function(paths, _origAdd, _internal) {
  519. var disableGlobbing = this.options.disableGlobbing;
  520. var cwd = this.options.cwd;
  521. this.closed = false;
  522. paths = flatten(arrify(paths));
  523. if (!paths.every(isString)) {
  524. throw new TypeError('Non-string provided as watch path: ' + paths);
  525. }
  526. if (cwd) paths = paths.map(function(path) {
  527. var absPath;
  528. if (isAbsolute(path)) {
  529. absPath = path;
  530. } else if (path[0] === '!') {
  531. absPath = '!' + sysPath.join(cwd, path.substring(1));
  532. } else {
  533. absPath = sysPath.join(cwd, path);
  534. }
  535. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  536. if (disableGlobbing || !isGlob(path)) {
  537. return absPath;
  538. } else {
  539. return normalizePath(absPath);
  540. }
  541. });
  542. // set aside negated glob strings
  543. paths = paths.filter(function(path) {
  544. if (path[0] === '!') {
  545. this._ignoredPaths[path.substring(1)] = true;
  546. } else {
  547. // if a path is being added that was previously ignored, stop ignoring it
  548. delete this._ignoredPaths[path];
  549. delete this._ignoredPaths[path + '/**'];
  550. // reset the cached userIgnored anymatch fn
  551. // to make ignoredPaths changes effective
  552. this._userIgnored = null;
  553. return true;
  554. }
  555. }, this);
  556. if (this.options.useFsEvents && FsEventsHandler.canUse()) {
  557. if (!this._readyCount) this._readyCount = paths.length;
  558. if (this.options.persistent) this._readyCount *= 2;
  559. paths.forEach(this._addToFsEvents, this);
  560. } else {
  561. if (!this._readyCount) this._readyCount = 0;
  562. this._readyCount += paths.length;
  563. asyncEach(paths, function(path, next) {
  564. this._addToNodeFs(path, !_internal, 0, 0, _origAdd, function(err, res) {
  565. if (res) this._emitReady();
  566. next(err, res);
  567. }.bind(this));
  568. }.bind(this), function(error, results) {
  569. results.forEach(function(item) {
  570. if (!item || this.closed) return;
  571. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  572. }, this);
  573. }.bind(this));
  574. }
  575. return this;
  576. };
  577. // Public method: Close watchers or start ignoring events from specified paths.
  578. // * paths - string or array of strings, file/directory paths and/or globs
  579. // Returns instance of FSWatcher for chaining.
  580. FSWatcher.prototype.unwatch = function(paths) {
  581. if (this.closed) return this;
  582. paths = flatten(arrify(paths));
  583. paths.forEach(function(path) {
  584. // convert to absolute path unless relative path already matches
  585. if (!isAbsolute(path) && !this._closers[path]) {
  586. if (this.options.cwd) path = sysPath.join(this.options.cwd, path);
  587. path = sysPath.resolve(path);
  588. }
  589. this._closePath(path);
  590. this._ignoredPaths[path] = true;
  591. if (path in this._watched) {
  592. this._ignoredPaths[path + '/**'] = true;
  593. }
  594. // reset the cached userIgnored anymatch fn
  595. // to make ignoredPaths changes effective
  596. this._userIgnored = null;
  597. }, this);
  598. return this;
  599. };
  600. // Public method: Close watchers and remove all listeners from watched paths.
  601. // Returns instance of FSWatcher for chaining.
  602. FSWatcher.prototype.close = function() {
  603. if (this.closed) return this;
  604. this.closed = true;
  605. Object.keys(this._closers).forEach(function(watchPath) {
  606. this._closers[watchPath]();
  607. delete this._closers[watchPath];
  608. }, this);
  609. this._watched = Object.create(null);
  610. this.removeAllListeners();
  611. return this;
  612. };
  613. // Public method: Expose list of watched paths
  614. // Returns object w/ dir paths as keys and arrays of contained paths as values.
  615. FSWatcher.prototype.getWatched = function() {
  616. var watchList = {};
  617. Object.keys(this._watched).forEach(function(dir) {
  618. var key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  619. watchList[key || '.'] = Object.keys(this._watched[dir]._items).sort();
  620. }.bind(this));
  621. return watchList;
  622. };
  623. // Attach watch handler prototype methods
  624. function importHandler(handler) {
  625. Object.keys(handler.prototype).forEach(function(method) {
  626. FSWatcher.prototype[method] = handler.prototype[method];
  627. });
  628. }
  629. importHandler(NodeFsHandler);
  630. if (FsEventsHandler.canUse()) importHandler(FsEventsHandler);
  631. // Export FSWatcher class
  632. exports.FSWatcher = FSWatcher;
  633. // Public function: Instantiates watcher with paths to be tracked.
  634. // * paths - string or array of strings, file/directory paths and/or globs
  635. // * options - object, chokidar options
  636. // Returns an instance of FSWatcher for chaining.
  637. exports.watch = function(paths, options) {
  638. return new FSWatcher(options).add(paths);
  639. };