e121c0fdb93f753f88892817527cfe6d81b38eb39f4d7a9f584b524c3b970654da67c78512585b06b88982331f64cca8b0dbd9b38f7835daad0ef0d489dad8 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. # Chokidar [![Weekly downloads](https://img.shields.io/npm/dw/chokidar.svg)](https://github.com/paulmillr/chokidar)
  2. > Minimal and efficient cross-platform file watching library
  3. ## Why?
  4. There are many reasons to prefer Chokidar to raw fs.watch / fs.watchFile in 2024:
  5. - Events are properly reported
  6. - macOS events report filenames
  7. - events are not reported twice
  8. - changes are reported as add / change / unlink instead of useless `rename`
  9. - Atomic writes are supported, using `atomic` option
  10. - Some file editors use them
  11. - Chunked writes are supported, using `awaitWriteFinish` option
  12. - Large files are commonly written in chunks
  13. - File / dir filtering is supported
  14. - Symbolic links are supported
  15. - Recursive watching is always supported, instead of partial when using raw events
  16. - Includes a way to limit recursion depth
  17. Chokidar relies on the Node.js core `fs` module, but when using
  18. `fs.watch` and `fs.watchFile` for watching, it normalizes the events it
  19. receives, often checking for truth by getting file stats and/or dir contents.
  20. The `fs.watch`-based implementation is the default, which
  21. avoids polling and keeps CPU usage down. Be advised that chokidar will initiate
  22. watchers recursively for everything within scope of the paths that have been
  23. specified, so be judicious about not wasting system resources by watching much
  24. more than needed. For some cases, `fs.watchFile`, which utilizes polling and uses more resources, is used.
  25. Made for [Brunch](https://brunch.io/) in 2012,
  26. it is now used in [~30 million repositories](https://www.npmjs.com/browse/depended/chokidar) and
  27. has proven itself in production environments.
  28. **Sep 2024 update:** v4 is out! It decreases dependency count from 13 to 1, removes
  29. support for globs, adds support for ESM / Common.js modules, and bumps minimum node.js version from v8 to v14.
  30. Check out [upgrading](#upgrading).
  31. ## Getting started
  32. Install with npm:
  33. ```sh
  34. npm install chokidar
  35. ```
  36. Use it in your code:
  37. ```javascript
  38. import chokidar from 'chokidar';
  39. // One-liner for current directory
  40. chokidar.watch('.').on('all', (event, path) => {
  41. console.log(event, path);
  42. });
  43. // Extended options
  44. // ----------------
  45. // Initialize watcher.
  46. const watcher = chokidar.watch('file, dir, or array', {
  47. ignored: (path, stats) => stats?.isFile() && !path.endsWith('.js'), // only watch js files
  48. persistent: true
  49. });
  50. // Something to use when events are received.
  51. const log = console.log.bind(console);
  52. // Add event listeners.
  53. watcher
  54. .on('add', path => log(`File ${path} has been added`))
  55. .on('change', path => log(`File ${path} has been changed`))
  56. .on('unlink', path => log(`File ${path} has been removed`));
  57. // More possible events.
  58. watcher
  59. .on('addDir', path => log(`Directory ${path} has been added`))
  60. .on('unlinkDir', path => log(`Directory ${path} has been removed`))
  61. .on('error', error => log(`Watcher error: ${error}`))
  62. .on('ready', () => log('Initial scan complete. Ready for changes'))
  63. .on('raw', (event, path, details) => { // internal
  64. log('Raw event info:', event, path, details);
  65. });
  66. // 'add', 'addDir' and 'change' events also receive stat() results as second
  67. // argument when available: https://nodejs.org/api/fs.html#fs_class_fs_stats
  68. watcher.on('change', (path, stats) => {
  69. if (stats) console.log(`File ${path} changed size to ${stats.size}`);
  70. });
  71. // Watch new files.
  72. watcher.add('new-file');
  73. watcher.add(['new-file-2', 'new-file-3']);
  74. // Get list of actual paths being watched on the filesystem
  75. let watchedPaths = watcher.getWatched();
  76. // Un-watch some files.
  77. await watcher.unwatch('new-file');
  78. // Stop watching. The method is async!
  79. await watcher.close().then(() => console.log('closed'));
  80. // Full list of options. See below for descriptions.
  81. // Do not use this example!
  82. chokidar.watch('file', {
  83. persistent: true,
  84. // ignore .txt files
  85. ignored: (file) => file.endsWith('.txt'),
  86. // watch only .txt files
  87. // ignored: (file, _stats) => _stats?.isFile() && !file.endsWith('.txt'),
  88. awaitWriteFinish: true, // emit single event when chunked writes are completed
  89. atomic: true, // emit proper events when "atomic writes" (mv _tmp file) are used
  90. // The options also allow specifying custom intervals in ms
  91. // awaitWriteFinish: {
  92. // stabilityThreshold: 2000,
  93. // pollInterval: 100
  94. // },
  95. // atomic: 100,
  96. interval: 100,
  97. binaryInterval: 300,
  98. cwd: '.',
  99. depth: 99,
  100. followSymlinks: true,
  101. ignoreInitial: false,
  102. ignorePermissionErrors: false,
  103. usePolling: false,
  104. alwaysStat: false,
  105. });
  106. ```
  107. `chokidar.watch(paths, [options])`
  108. * `paths` (string or array of strings). Paths to files, dirs to be watched
  109. recursively.
  110. * `options` (object) Options object as defined below:
  111. #### Persistence
  112. * `persistent` (default: `true`). Indicates whether the process
  113. should continue to run as long as files are being watched.
  114. #### Path filtering
  115. * `ignored` function, regex, or path. Defines files/paths to be ignored.
  116. The whole relative or absolute path is tested, not just filename. If a function with two arguments
  117. is provided, it gets called twice per path - once with a single argument (the path), second
  118. time with two arguments (the path and the
  119. [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats)
  120. object of that path).
  121. * `ignoreInitial` (default: `false`). If set to `false` then `add`/`addDir` events are also emitted for matching paths while
  122. instantiating the watching as chokidar discovers these file paths (before the `ready` event).
  123. * `followSymlinks` (default: `true`). When `false`, only the
  124. symlinks themselves will be watched for changes instead of following
  125. the link references and bubbling events through the link's path.
  126. * `cwd` (no default). The base directory from which watch `paths` are to be
  127. derived. Paths emitted with events will be relative to this.
  128. #### Performance
  129. * `usePolling` (default: `false`).
  130. Whether to use fs.watchFile (backed by polling), or fs.watch. If polling
  131. leads to high CPU utilization, consider setting this to `false`. It is
  132. typically necessary to **set this to `true` to successfully watch files over
  133. a network**, and it may be necessary to successfully watch files in other
  134. non-standard situations. Setting to `true` explicitly on MacOS overrides the
  135. `useFsEvents` default. You may also set the CHOKIDAR_USEPOLLING env variable
  136. to true (1) or false (0) in order to override this option.
  137. * _Polling-specific settings_ (effective when `usePolling: true`)
  138. * `interval` (default: `100`). Interval of file system polling, in milliseconds. You may also
  139. set the CHOKIDAR_INTERVAL env variable to override this option.
  140. * `binaryInterval` (default: `300`). Interval of file system
  141. polling for binary files.
  142. ([see list of binary extensions](https://github.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
  143. * `alwaysStat` (default: `false`). If relying upon the
  144. [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats)
  145. object that may get passed with `add`, `addDir`, and `change` events, set
  146. this to `true` to ensure it is provided even in cases where it wasn't
  147. already available from the underlying watch events.
  148. * `depth` (default: `undefined`). If set, limits how many levels of
  149. subdirectories will be traversed.
  150. * `awaitWriteFinish` (default: `false`).
  151. By default, the `add` event will fire when a file first appears on disk, before
  152. the entire file has been written. Furthermore, in some cases some `change`
  153. events will be emitted while the file is being written. In some cases,
  154. especially when watching for large files there will be a need to wait for the
  155. write operation to finish before responding to a file creation or modification.
  156. Setting `awaitWriteFinish` to `true` (or a truthy value) will poll file size,
  157. holding its `add` and `change` events until the size does not change for a
  158. configurable amount of time. The appropriate duration setting is heavily
  159. dependent on the OS and hardware. For accurate detection this parameter should
  160. be relatively high, making file watching much less responsive.
  161. Use with caution.
  162. * *`options.awaitWriteFinish` can be set to an object in order to adjust
  163. timing params:*
  164. * `awaitWriteFinish.stabilityThreshold` (default: 2000). Amount of time in
  165. milliseconds for a file size to remain constant before emitting its event.
  166. * `awaitWriteFinish.pollInterval` (default: 100). File size polling interval, in milliseconds.
  167. #### Errors
  168. * `ignorePermissionErrors` (default: `false`). Indicates whether to watch files
  169. that don't have read permissions if possible. If watching fails due to `EPERM`
  170. or `EACCES` with this set to `true`, the errors will be suppressed silently.
  171. * `atomic` (default: `true` if `useFsEvents` and `usePolling` are `false`).
  172. Automatically filters out artifacts that occur when using editors that use
  173. "atomic writes" instead of writing directly to the source file. If a file is
  174. re-added within 100 ms of being deleted, Chokidar emits a `change` event
  175. rather than `unlink` then `add`. If the default of 100 ms does not work well
  176. for you, you can override it by setting `atomic` to a custom value, in
  177. milliseconds.
  178. ### Methods & Events
  179. `chokidar.watch()` produces an instance of `FSWatcher`. Methods of `FSWatcher`:
  180. * `.add(path / paths)`: Add files, directories for tracking.
  181. Takes an array of strings or just one string.
  182. * `.on(event, callback)`: Listen for an FS event.
  183. Available events: `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `ready`,
  184. `raw`, `error`.
  185. Additionally `all` is available which gets emitted with the underlying event
  186. name and path for every event other than `ready`, `raw`, and `error`. `raw` is internal, use it carefully.
  187. * `.unwatch(path / paths)`: Stop watching files or directories.
  188. Takes an array of strings or just one string.
  189. * `.close()`: **async** Removes all listeners from watched files. Asynchronous, returns Promise. Use with `await` to ensure bugs don't happen.
  190. * `.getWatched()`: Returns an object representing all the paths on the file
  191. system being watched by this `FSWatcher` instance. The object's keys are all the
  192. directories (using absolute paths unless the `cwd` option was used), and the
  193. values are arrays of the names of the items contained in each directory.
  194. ### CLI
  195. Check out third party [chokidar-cli](https://github.com/open-cli-tools/chokidar-cli),
  196. which allows to execute a command on each change, or get a stdio stream of change events.
  197. ## Troubleshooting
  198. Sometimes, Chokidar runs out of file handles, causing `EMFILE` and `ENOSP` errors:
  199. * `bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell`
  200. * `Error: watch /home/ ENOSPC`
  201. There are two things that can cause it.
  202. 1. Exhausted file handles for generic fs operations
  203. - Can be solved by using [graceful-fs](https://www.npmjs.com/package/graceful-fs),
  204. which can monkey-patch native `fs` module used by chokidar: `let fs = require('fs'); let grfs = require('graceful-fs'); grfs.gracefulify(fs);`
  205. - Can also be solved by tuning OS: `echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p`.
  206. 2. Exhausted file handles for `fs.watch`
  207. - Can't seem to be solved by graceful-fs or OS tuning
  208. - It's possible to start using `usePolling: true`, which will switch backend to resource-intensive `fs.watchFile`
  209. All fsevents-related issues (`WARN optional dep failed`, `fsevents is not a constructor`) are solved by upgrading to v4+.
  210. ## Changelog
  211. - **v4 (Sep 2024):** remove glob support and bundled fsevents. Decrease dependency count from 13 to 1. Rewrite in typescript. Bumps minimum node.js requirement to v14+
  212. - **v3 (Apr 2019):** massive CPU & RAM consumption improvements; reduces deps / package size by a factor of 17x and bumps Node.js requirement to v8.16+.
  213. - **v2 (Dec 2017):** globs are now posix-style-only. Tons of bugfixes.
  214. - **v1 (Apr 2015):** glob support, symlink support, tons of bugfixes. Node 0.8+ is supported
  215. - **v0.1 (Apr 2012):** Initial release, extracted from [Brunch](https://github.com/brunch/brunch/blob/9847a065aea300da99bd0753f90354cde9de1261/src/helpers.coffee#L66)
  216. ### Upgrading
  217. If you've used globs before and want do replicate the functionality with v4:
  218. ```js
  219. // v3
  220. chok.watch('**/*.js');
  221. chok.watch("./directory/**/*");
  222. // v4
  223. chok.watch('.', {
  224. ignored: (path, stats) => stats?.isFile() && !path.endsWith('.js'), // only watch js files
  225. });
  226. chok.watch('./directory');
  227. // other way
  228. import { glob } from 'node:fs/promises';
  229. const watcher = watch(await Array.fromAsync(glob('**/*.js')));
  230. // unwatching
  231. // v3
  232. chok.unwatch('**/*.js');
  233. // v4
  234. chok.unwatch(await glob('**/*.js'));
  235. ```
  236. ## Also
  237. Why was chokidar named this way? What's the meaning behind it?
  238. >Chowkidar is a transliteration of a Hindi word meaning 'watchman, gatekeeper', चौकीदार. This ultimately comes from Sanskrit _ चतुष्क_ (crossway, quadrangle, consisting-of-four). This word is also used in other languages like Urdu as (چوکیدار) which is widely used in Pakistan and India.
  239. ## License
  240. MIT (c) Paul Miller (<https://paulmillr.com>), see [LICENSE](LICENSE) file.