handler.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. import { watchFile, unwatchFile, watch as fs_watch } from 'fs';
  2. import { open, stat, lstat, realpath as fsrealpath } from 'fs/promises';
  3. import * as sysPath from 'path';
  4. import { type as osType } from 'os';
  5. export const STR_DATA = 'data';
  6. export const STR_END = 'end';
  7. export const STR_CLOSE = 'close';
  8. export const EMPTY_FN = () => { };
  9. export const IDENTITY_FN = (val) => val;
  10. const pl = process.platform;
  11. export const isWindows = pl === 'win32';
  12. export const isMacos = pl === 'darwin';
  13. export const isLinux = pl === 'linux';
  14. export const isFreeBSD = pl === 'freebsd';
  15. export const isIBMi = osType() === 'OS400';
  16. export const EVENTS = {
  17. ALL: 'all',
  18. READY: 'ready',
  19. ADD: 'add',
  20. CHANGE: 'change',
  21. ADD_DIR: 'addDir',
  22. UNLINK: 'unlink',
  23. UNLINK_DIR: 'unlinkDir',
  24. RAW: 'raw',
  25. ERROR: 'error',
  26. };
  27. const EV = EVENTS;
  28. const THROTTLE_MODE_WATCH = 'watch';
  29. const statMethods = { lstat, stat };
  30. const KEY_LISTENERS = 'listeners';
  31. const KEY_ERR = 'errHandlers';
  32. const KEY_RAW = 'rawEmitters';
  33. const HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
  34. // prettier-ignore
  35. const binaryExtensions = new Set([
  36. '3dm', '3ds', '3g2', '3gp', '7z', 'a', 'aac', 'adp', 'afdesign', 'afphoto', 'afpub', 'ai',
  37. 'aif', 'aiff', 'alz', 'ape', 'apk', 'appimage', 'ar', 'arj', 'asf', 'au', 'avi',
  38. 'bak', 'baml', 'bh', 'bin', 'bk', 'bmp', 'btif', 'bz2', 'bzip2',
  39. 'cab', 'caf', 'cgm', 'class', 'cmx', 'cpio', 'cr2', 'cur', 'dat', 'dcm', 'deb', 'dex', 'djvu',
  40. 'dll', 'dmg', 'dng', 'doc', 'docm', 'docx', 'dot', 'dotm', 'dra', 'DS_Store', 'dsk', 'dts',
  41. 'dtshd', 'dvb', 'dwg', 'dxf',
  42. 'ecelp4800', 'ecelp7470', 'ecelp9600', 'egg', 'eol', 'eot', 'epub', 'exe',
  43. 'f4v', 'fbs', 'fh', 'fla', 'flac', 'flatpak', 'fli', 'flv', 'fpx', 'fst', 'fvt',
  44. 'g3', 'gh', 'gif', 'graffle', 'gz', 'gzip',
  45. 'h261', 'h263', 'h264', 'icns', 'ico', 'ief', 'img', 'ipa', 'iso',
  46. 'jar', 'jpeg', 'jpg', 'jpgv', 'jpm', 'jxr', 'key', 'ktx',
  47. 'lha', 'lib', 'lvp', 'lz', 'lzh', 'lzma', 'lzo',
  48. 'm3u', 'm4a', 'm4v', 'mar', 'mdi', 'mht', 'mid', 'midi', 'mj2', 'mka', 'mkv', 'mmr', 'mng',
  49. 'mobi', 'mov', 'movie', 'mp3',
  50. 'mp4', 'mp4a', 'mpeg', 'mpg', 'mpga', 'mxu',
  51. 'nef', 'npx', 'numbers', 'nupkg',
  52. 'o', 'odp', 'ods', 'odt', 'oga', 'ogg', 'ogv', 'otf', 'ott',
  53. 'pages', 'pbm', 'pcx', 'pdb', 'pdf', 'pea', 'pgm', 'pic', 'png', 'pnm', 'pot', 'potm',
  54. 'potx', 'ppa', 'ppam',
  55. 'ppm', 'pps', 'ppsm', 'ppsx', 'ppt', 'pptm', 'pptx', 'psd', 'pya', 'pyc', 'pyo', 'pyv',
  56. 'qt',
  57. 'rar', 'ras', 'raw', 'resources', 'rgb', 'rip', 'rlc', 'rmf', 'rmvb', 'rpm', 'rtf', 'rz',
  58. 's3m', 's7z', 'scpt', 'sgi', 'shar', 'snap', 'sil', 'sketch', 'slk', 'smv', 'snk', 'so',
  59. 'stl', 'suo', 'sub', 'swf',
  60. 'tar', 'tbz', 'tbz2', 'tga', 'tgz', 'thmx', 'tif', 'tiff', 'tlz', 'ttc', 'ttf', 'txz',
  61. 'udf', 'uvh', 'uvi', 'uvm', 'uvp', 'uvs', 'uvu',
  62. 'viv', 'vob',
  63. 'war', 'wav', 'wax', 'wbmp', 'wdp', 'weba', 'webm', 'webp', 'whl', 'wim', 'wm', 'wma',
  64. 'wmv', 'wmx', 'woff', 'woff2', 'wrm', 'wvx',
  65. 'xbm', 'xif', 'xla', 'xlam', 'xls', 'xlsb', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx', 'xm',
  66. 'xmind', 'xpi', 'xpm', 'xwd', 'xz',
  67. 'z', 'zip', 'zipx',
  68. ]);
  69. const isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase());
  70. // TODO: emit errors properly. Example: EMFILE on Macos.
  71. const foreach = (val, fn) => {
  72. if (val instanceof Set) {
  73. val.forEach(fn);
  74. }
  75. else {
  76. fn(val);
  77. }
  78. };
  79. const addAndConvert = (main, prop, item) => {
  80. let container = main[prop];
  81. if (!(container instanceof Set)) {
  82. main[prop] = container = new Set([container]);
  83. }
  84. container.add(item);
  85. };
  86. const clearItem = (cont) => (key) => {
  87. const set = cont[key];
  88. if (set instanceof Set) {
  89. set.clear();
  90. }
  91. else {
  92. delete cont[key];
  93. }
  94. };
  95. const delFromSet = (main, prop, item) => {
  96. const container = main[prop];
  97. if (container instanceof Set) {
  98. container.delete(item);
  99. }
  100. else if (container === item) {
  101. delete main[prop];
  102. }
  103. };
  104. const isEmptySet = (val) => (val instanceof Set ? val.size === 0 : !val);
  105. const FsWatchInstances = new Map();
  106. /**
  107. * Instantiates the fs_watch interface
  108. * @param path to be watched
  109. * @param options to be passed to fs_watch
  110. * @param listener main event handler
  111. * @param errHandler emits info about errors
  112. * @param emitRaw emits raw event data
  113. * @returns {NativeFsWatcher}
  114. */
  115. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  116. const handleEvent = (rawEvent, evPath) => {
  117. listener(path);
  118. emitRaw(rawEvent, evPath, { watchedPath: path });
  119. // emit based on events occurring for files from a directory's watcher in
  120. // case the file's watcher misses it (and rely on throttling to de-dupe)
  121. if (evPath && path !== evPath) {
  122. fsWatchBroadcast(sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath));
  123. }
  124. };
  125. try {
  126. return fs_watch(path, {
  127. persistent: options.persistent,
  128. }, handleEvent);
  129. }
  130. catch (error) {
  131. errHandler(error);
  132. return undefined;
  133. }
  134. }
  135. /**
  136. * Helper for passing fs_watch event data to a collection of listeners
  137. * @param fullPath absolute path bound to fs_watch instance
  138. */
  139. const fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
  140. const cont = FsWatchInstances.get(fullPath);
  141. if (!cont)
  142. return;
  143. foreach(cont[listenerType], (listener) => {
  144. listener(val1, val2, val3);
  145. });
  146. };
  147. /**
  148. * Instantiates the fs_watch interface or binds listeners
  149. * to an existing one covering the same file system entry
  150. * @param path
  151. * @param fullPath absolute path
  152. * @param options to be passed to fs_watch
  153. * @param handlers container for event listener functions
  154. */
  155. const setFsWatchListener = (path, fullPath, options, handlers) => {
  156. const { listener, errHandler, rawEmitter } = handlers;
  157. let cont = FsWatchInstances.get(fullPath);
  158. let watcher;
  159. if (!options.persistent) {
  160. watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
  161. if (!watcher)
  162. return;
  163. return watcher.close.bind(watcher);
  164. }
  165. if (cont) {
  166. addAndConvert(cont, KEY_LISTENERS, listener);
  167. addAndConvert(cont, KEY_ERR, errHandler);
  168. addAndConvert(cont, KEY_RAW, rawEmitter);
  169. }
  170. else {
  171. watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, // no need to use broadcast here
  172. fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
  173. if (!watcher)
  174. return;
  175. watcher.on(EV.ERROR, async (error) => {
  176. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  177. if (cont)
  178. cont.watcherUnusable = true; // documented since Node 10.4.1
  179. // Workaround for https://github.com/joyent/node/issues/4337
  180. if (isWindows && error.code === 'EPERM') {
  181. try {
  182. const fd = await open(path, 'r');
  183. await fd.close();
  184. broadcastErr(error);
  185. }
  186. catch (err) {
  187. // do nothing
  188. }
  189. }
  190. else {
  191. broadcastErr(error);
  192. }
  193. });
  194. cont = {
  195. listeners: listener,
  196. errHandlers: errHandler,
  197. rawEmitters: rawEmitter,
  198. watcher,
  199. };
  200. FsWatchInstances.set(fullPath, cont);
  201. }
  202. // const index = cont.listeners.indexOf(listener);
  203. // removes this instance's listeners and closes the underlying fs_watch
  204. // instance if there are no more listeners left
  205. return () => {
  206. delFromSet(cont, KEY_LISTENERS, listener);
  207. delFromSet(cont, KEY_ERR, errHandler);
  208. delFromSet(cont, KEY_RAW, rawEmitter);
  209. if (isEmptySet(cont.listeners)) {
  210. // Check to protect against issue gh-730.
  211. // if (cont.watcherUnusable) {
  212. cont.watcher.close();
  213. // }
  214. FsWatchInstances.delete(fullPath);
  215. HANDLER_KEYS.forEach(clearItem(cont));
  216. // @ts-ignore
  217. cont.watcher = undefined;
  218. Object.freeze(cont);
  219. }
  220. };
  221. };
  222. // fs_watchFile helpers
  223. // object to hold per-process fs_watchFile instances
  224. // (may be shared across chokidar FSWatcher instances)
  225. const FsWatchFileInstances = new Map();
  226. /**
  227. * Instantiates the fs_watchFile interface or binds listeners
  228. * to an existing one covering the same file system entry
  229. * @param path to be watched
  230. * @param fullPath absolute path
  231. * @param options options to be passed to fs_watchFile
  232. * @param handlers container for event listener functions
  233. * @returns closer
  234. */
  235. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  236. const { listener, rawEmitter } = handlers;
  237. let cont = FsWatchFileInstances.get(fullPath);
  238. // let listeners = new Set();
  239. // let rawEmitters = new Set();
  240. const copts = cont && cont.options;
  241. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  242. // "Upgrade" the watcher to persistence or a quicker interval.
  243. // This creates some unlikely edge case issues if the user mixes
  244. // settings in a very weird way, but solving for those cases
  245. // doesn't seem worthwhile for the added complexity.
  246. // listeners = cont.listeners;
  247. // rawEmitters = cont.rawEmitters;
  248. unwatchFile(fullPath);
  249. cont = undefined;
  250. }
  251. if (cont) {
  252. addAndConvert(cont, KEY_LISTENERS, listener);
  253. addAndConvert(cont, KEY_RAW, rawEmitter);
  254. }
  255. else {
  256. // TODO
  257. // listeners.add(listener);
  258. // rawEmitters.add(rawEmitter);
  259. cont = {
  260. listeners: listener,
  261. rawEmitters: rawEmitter,
  262. options,
  263. watcher: watchFile(fullPath, options, (curr, prev) => {
  264. foreach(cont.rawEmitters, (rawEmitter) => {
  265. rawEmitter(EV.CHANGE, fullPath, { curr, prev });
  266. });
  267. const currmtime = curr.mtimeMs;
  268. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
  269. foreach(cont.listeners, (listener) => listener(path, curr));
  270. }
  271. }),
  272. };
  273. FsWatchFileInstances.set(fullPath, cont);
  274. }
  275. // const index = cont.listeners.indexOf(listener);
  276. // Removes this instance's listeners and closes the underlying fs_watchFile
  277. // instance if there are no more listeners left.
  278. return () => {
  279. delFromSet(cont, KEY_LISTENERS, listener);
  280. delFromSet(cont, KEY_RAW, rawEmitter);
  281. if (isEmptySet(cont.listeners)) {
  282. FsWatchFileInstances.delete(fullPath);
  283. unwatchFile(fullPath);
  284. cont.options = cont.watcher = undefined;
  285. Object.freeze(cont);
  286. }
  287. };
  288. };
  289. /**
  290. * @mixin
  291. */
  292. export class NodeFsHandler {
  293. constructor(fsW) {
  294. this.fsw = fsW;
  295. this._boundHandleError = (error) => fsW._handleError(error);
  296. }
  297. /**
  298. * Watch file for changes with fs_watchFile or fs_watch.
  299. * @param path to file or dir
  300. * @param listener on fs change
  301. * @returns closer for the watcher instance
  302. */
  303. _watchWithNodeFs(path, listener) {
  304. const opts = this.fsw.options;
  305. const directory = sysPath.dirname(path);
  306. const basename = sysPath.basename(path);
  307. const parent = this.fsw._getWatchedDir(directory);
  308. parent.add(basename);
  309. const absolutePath = sysPath.resolve(path);
  310. const options = {
  311. persistent: opts.persistent,
  312. };
  313. if (!listener)
  314. listener = EMPTY_FN;
  315. let closer;
  316. if (opts.usePolling) {
  317. const enableBin = opts.interval !== opts.binaryInterval;
  318. options.interval = enableBin && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;
  319. closer = setFsWatchFileListener(path, absolutePath, options, {
  320. listener,
  321. rawEmitter: this.fsw._emitRaw,
  322. });
  323. }
  324. else {
  325. closer = setFsWatchListener(path, absolutePath, options, {
  326. listener,
  327. errHandler: this._boundHandleError,
  328. rawEmitter: this.fsw._emitRaw,
  329. });
  330. }
  331. return closer;
  332. }
  333. /**
  334. * Watch a file and emit add event if warranted.
  335. * @returns closer for the watcher instance
  336. */
  337. _handleFile(file, stats, initialAdd) {
  338. if (this.fsw.closed) {
  339. return;
  340. }
  341. const dirname = sysPath.dirname(file);
  342. const basename = sysPath.basename(file);
  343. const parent = this.fsw._getWatchedDir(dirname);
  344. // stats is always present
  345. let prevStats = stats;
  346. // if the file is already being watched, do nothing
  347. if (parent.has(basename))
  348. return;
  349. const listener = async (path, newStats) => {
  350. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))
  351. return;
  352. if (!newStats || newStats.mtimeMs === 0) {
  353. try {
  354. const newStats = await stat(file);
  355. if (this.fsw.closed)
  356. return;
  357. // Check that change event was not fired because of changed only accessTime.
  358. const at = newStats.atimeMs;
  359. const mt = newStats.mtimeMs;
  360. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  361. this.fsw._emit(EV.CHANGE, file, newStats);
  362. }
  363. if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats.ino) {
  364. this.fsw._closeFile(path);
  365. prevStats = newStats;
  366. const closer = this._watchWithNodeFs(file, listener);
  367. if (closer)
  368. this.fsw._addPathCloser(path, closer);
  369. }
  370. else {
  371. prevStats = newStats;
  372. }
  373. }
  374. catch (error) {
  375. // Fix issues where mtime is null but file is still present
  376. this.fsw._remove(dirname, basename);
  377. }
  378. // add is about to be emitted if file not already tracked in parent
  379. }
  380. else if (parent.has(basename)) {
  381. // Check that change event was not fired because of changed only accessTime.
  382. const at = newStats.atimeMs;
  383. const mt = newStats.mtimeMs;
  384. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  385. this.fsw._emit(EV.CHANGE, file, newStats);
  386. }
  387. prevStats = newStats;
  388. }
  389. };
  390. // kick off the watcher
  391. const closer = this._watchWithNodeFs(file, listener);
  392. // emit an add event if we're supposed to
  393. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  394. if (!this.fsw._throttle(EV.ADD, file, 0))
  395. return;
  396. this.fsw._emit(EV.ADD, file, stats);
  397. }
  398. return closer;
  399. }
  400. /**
  401. * Handle symlinks encountered while reading a dir.
  402. * @param entry returned by readdirp
  403. * @param directory path of dir being read
  404. * @param path of this item
  405. * @param item basename of this item
  406. * @returns true if no more processing is needed for this entry.
  407. */
  408. async _handleSymlink(entry, directory, path, item) {
  409. if (this.fsw.closed) {
  410. return;
  411. }
  412. const full = entry.fullPath;
  413. const dir = this.fsw._getWatchedDir(directory);
  414. if (!this.fsw.options.followSymlinks) {
  415. // watch symlink directly (don't follow) and detect changes
  416. this.fsw._incrReadyCount();
  417. let linkPath;
  418. try {
  419. linkPath = await fsrealpath(path);
  420. }
  421. catch (e) {
  422. this.fsw._emitReady();
  423. return true;
  424. }
  425. if (this.fsw.closed)
  426. return;
  427. if (dir.has(item)) {
  428. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  429. this.fsw._symlinkPaths.set(full, linkPath);
  430. this.fsw._emit(EV.CHANGE, path, entry.stats);
  431. }
  432. }
  433. else {
  434. dir.add(item);
  435. this.fsw._symlinkPaths.set(full, linkPath);
  436. this.fsw._emit(EV.ADD, path, entry.stats);
  437. }
  438. this.fsw._emitReady();
  439. return true;
  440. }
  441. // don't follow the same symlink more than once
  442. if (this.fsw._symlinkPaths.has(full)) {
  443. return true;
  444. }
  445. this.fsw._symlinkPaths.set(full, true);
  446. }
  447. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  448. // Normalize the directory name on Windows
  449. directory = sysPath.join(directory, '');
  450. throttler = this.fsw._throttle('readdir', directory, 1000);
  451. if (!throttler)
  452. return;
  453. const previous = this.fsw._getWatchedDir(wh.path);
  454. const current = new Set();
  455. let stream = this.fsw._readdirp(directory, {
  456. fileFilter: (entry) => wh.filterPath(entry),
  457. directoryFilter: (entry) => wh.filterDir(entry),
  458. });
  459. if (!stream)
  460. return;
  461. stream
  462. .on(STR_DATA, async (entry) => {
  463. if (this.fsw.closed) {
  464. stream = undefined;
  465. return;
  466. }
  467. const item = entry.path;
  468. let path = sysPath.join(directory, item);
  469. current.add(item);
  470. if (entry.stats.isSymbolicLink() &&
  471. (await this._handleSymlink(entry, directory, path, item))) {
  472. return;
  473. }
  474. if (this.fsw.closed) {
  475. stream = undefined;
  476. return;
  477. }
  478. // Files that present in current directory snapshot
  479. // but absent in previous are added to watch list and
  480. // emit `add` event.
  481. if (item === target || (!target && !previous.has(item))) {
  482. this.fsw._incrReadyCount();
  483. // ensure relativeness of path is preserved in case of watcher reuse
  484. path = sysPath.join(dir, sysPath.relative(dir, path));
  485. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  486. }
  487. })
  488. .on(EV.ERROR, this._boundHandleError);
  489. return new Promise((resolve, reject) => {
  490. if (!stream)
  491. return reject();
  492. stream.once(STR_END, () => {
  493. if (this.fsw.closed) {
  494. stream = undefined;
  495. return;
  496. }
  497. const wasThrottled = throttler ? throttler.clear() : false;
  498. resolve(undefined);
  499. // Files that absent in current directory snapshot
  500. // but present in previous emit `remove` event
  501. // and are removed from @watched[directory].
  502. previous
  503. .getChildren()
  504. .filter((item) => {
  505. return item !== directory && !current.has(item);
  506. })
  507. .forEach((item) => {
  508. this.fsw._remove(directory, item);
  509. });
  510. stream = undefined;
  511. // one more time for any missed in case changes came in extremely quickly
  512. if (wasThrottled)
  513. this._handleRead(directory, false, wh, target, dir, depth, throttler);
  514. });
  515. });
  516. }
  517. /**
  518. * Read directory to add / remove files from `@watched` list and re-read it on change.
  519. * @param dir fs path
  520. * @param stats
  521. * @param initialAdd
  522. * @param depth relative to user-supplied path
  523. * @param target child path targeted for watch
  524. * @param wh Common watch helpers for this path
  525. * @param realpath
  526. * @returns closer for the watcher instance.
  527. */
  528. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  529. const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
  530. const tracked = parentDir.has(sysPath.basename(dir));
  531. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  532. this.fsw._emit(EV.ADD_DIR, dir, stats);
  533. }
  534. // ensure dir is tracked (harmless if redundant)
  535. parentDir.add(sysPath.basename(dir));
  536. this.fsw._getWatchedDir(dir);
  537. let throttler;
  538. let closer;
  539. const oDepth = this.fsw.options.depth;
  540. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  541. if (!target) {
  542. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  543. if (this.fsw.closed)
  544. return;
  545. }
  546. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  547. // if current directory is removed, do nothing
  548. if (stats && stats.mtimeMs === 0)
  549. return;
  550. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  551. });
  552. }
  553. return closer;
  554. }
  555. /**
  556. * Handle added file, directory, or glob pattern.
  557. * Delegates call to _handleFile / _handleDir after checks.
  558. * @param path to file or ir
  559. * @param initialAdd was the file added at watch instantiation?
  560. * @param priorWh depth relative to user-supplied path
  561. * @param depth Child path actually targeted for watch
  562. * @param target Child path actually targeted for watch
  563. */
  564. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  565. const ready = this.fsw._emitReady;
  566. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  567. ready();
  568. return false;
  569. }
  570. const wh = this.fsw._getWatchHelpers(path);
  571. if (priorWh) {
  572. wh.filterPath = (entry) => priorWh.filterPath(entry);
  573. wh.filterDir = (entry) => priorWh.filterDir(entry);
  574. }
  575. // evaluate what is at the path we're being asked to watch
  576. try {
  577. const stats = await statMethods[wh.statMethod](wh.watchPath);
  578. if (this.fsw.closed)
  579. return;
  580. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  581. ready();
  582. return false;
  583. }
  584. const follow = this.fsw.options.followSymlinks;
  585. let closer;
  586. if (stats.isDirectory()) {
  587. const absPath = sysPath.resolve(path);
  588. const targetPath = follow ? await fsrealpath(path) : path;
  589. if (this.fsw.closed)
  590. return;
  591. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  592. if (this.fsw.closed)
  593. return;
  594. // preserve this symlink's target path
  595. if (absPath !== targetPath && targetPath !== undefined) {
  596. this.fsw._symlinkPaths.set(absPath, targetPath);
  597. }
  598. }
  599. else if (stats.isSymbolicLink()) {
  600. const targetPath = follow ? await fsrealpath(path) : path;
  601. if (this.fsw.closed)
  602. return;
  603. const parent = sysPath.dirname(wh.watchPath);
  604. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  605. this.fsw._emit(EV.ADD, wh.watchPath, stats);
  606. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  607. if (this.fsw.closed)
  608. return;
  609. // preserve this symlink's target path
  610. if (targetPath !== undefined) {
  611. this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);
  612. }
  613. }
  614. else {
  615. closer = this._handleFile(wh.watchPath, stats, initialAdd);
  616. }
  617. ready();
  618. if (closer)
  619. this.fsw._addPathCloser(path, closer);
  620. return false;
  621. }
  622. catch (error) {
  623. if (this.fsw._handleError(error)) {
  624. ready();
  625. return path;
  626. }
  627. }
  628. }
  629. }