index.js 22 KB

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