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

308 lines
14 KiB

2 years ago
  1. # Chokidar [![Weekly downloads](https://img.shields.io/npm/dw/chokidar.svg)](https://github.com/paulmillr/chokidar) [![Yearly downloads](https://img.shields.io/npm/dy/chokidar.svg)](https://github.com/paulmillr/chokidar)
  2. > Minimal and efficient cross-platform file watching library
  3. [![NPM](https://nodei.co/npm/chokidar.png)](https://www.npmjs.com/package/chokidar)
  4. ## Why?
  5. Node.js `fs.watch`:
  6. * Doesn't report filenames on MacOS.
  7. * Doesn't report events at all when using editors like Sublime on MacOS.
  8. * Often reports events twice.
  9. * Emits most changes as `rename`.
  10. * Does not provide an easy way to recursively watch file trees.
  11. * Does not support recursive watching on Linux.
  12. Node.js `fs.watchFile`:
  13. * Almost as bad at event handling.
  14. * Also does not provide any recursive watching.
  15. * Results in high CPU utilization.
  16. Chokidar resolves these problems.
  17. Initially made for **[Brunch](https://brunch.io/)** (an ultra-swift web app build tool), it is now used in
  18. [Microsoft's Visual Studio Code](https://github.com/microsoft/vscode),
  19. [gulp](https://github.com/gulpjs/gulp/),
  20. [karma](https://karma-runner.github.io/),
  21. [PM2](https://github.com/Unitech/PM2),
  22. [browserify](http://browserify.org/),
  23. [webpack](https://webpack.github.io/),
  24. [BrowserSync](https://www.browsersync.io/),
  25. and [many others](https://www.npmjs.com/browse/depended/chokidar).
  26. It has proven itself in production environments.
  27. Version 3 is out! Check out our blog post about it: [Chokidar 3: How to save 32TB of traffic every week](https://paulmillr.com/posts/chokidar-3-save-32tb-of-traffic/)
  28. ## How?
  29. Chokidar does still rely on the Node.js core `fs` module, but when using
  30. `fs.watch` and `fs.watchFile` for watching, it normalizes the events it
  31. receives, often checking for truth by getting file stats and/or dir contents.
  32. On MacOS, chokidar by default uses a native extension exposing the Darwin
  33. `FSEvents` API. This provides very efficient recursive watching compared with
  34. implementations like `kqueue` available on most \*nix platforms. Chokidar still
  35. does have to do some work to normalize the events received that way as well.
  36. On most other platforms, the `fs.watch`-based implementation is the default, which
  37. avoids polling and keeps CPU usage down. Be advised that chokidar will initiate
  38. watchers recursively for everything within scope of the paths that have been
  39. specified, so be judicious about not wasting system resources by watching much
  40. more than needed.
  41. ## Getting started
  42. Install with npm:
  43. ```sh
  44. npm install chokidar
  45. ```
  46. Then `require` and use it in your code:
  47. ```javascript
  48. const chokidar = require('chokidar');
  49. // One-liner for current directory
  50. chokidar.watch('.').on('all', (event, path) => {
  51. console.log(event, path);
  52. });
  53. ```
  54. ## API
  55. ```javascript
  56. // Example of a more typical implementation structure
  57. // Initialize watcher.
  58. const watcher = chokidar.watch('file, dir, glob, or array', {
  59. ignored: /(^|[\/\\])\../, // ignore dotfiles
  60. persistent: true
  61. });
  62. // Something to use when events are received.
  63. const log = console.log.bind(console);
  64. // Add event listeners.
  65. watcher
  66. .on('add', path => log(`File ${path} has been added`))
  67. .on('change', path => log(`File ${path} has been changed`))
  68. .on('unlink', path => log(`File ${path} has been removed`));
  69. // More possible events.
  70. watcher
  71. .on('addDir', path => log(`Directory ${path} has been added`))
  72. .on('unlinkDir', path => log(`Directory ${path} has been removed`))
  73. .on('error', error => log(`Watcher error: ${error}`))
  74. .on('ready', () => log('Initial scan complete. Ready for changes'))
  75. .on('raw', (event, path, details) => { // internal
  76. log('Raw event info:', event, path, details);
  77. });
  78. // 'add', 'addDir' and 'change' events also receive stat() results as second
  79. // argument when available: https://nodejs.org/api/fs.html#fs_class_fs_stats
  80. watcher.on('change', (path, stats) => {
  81. if (stats) console.log(`File ${path} changed size to ${stats.size}`);
  82. });
  83. // Watch new files.
  84. watcher.add('new-file');
  85. watcher.add(['new-file-2', 'new-file-3', '**/other-file*']);
  86. // Get list of actual paths being watched on the filesystem
  87. var watchedPaths = watcher.getWatched();
  88. // Un-watch some files.
  89. await watcher.unwatch('new-file*');
  90. // Stop watching.
  91. // The method is async!
  92. watcher.close().then(() => console.log('closed'));
  93. // Full list of options. See below for descriptions.
  94. // Do not use this example!
  95. chokidar.watch('file', {
  96. persistent: true,
  97. ignored: '*.txt',
  98. ignoreInitial: false,
  99. followSymlinks: true,
  100. cwd: '.',
  101. disableGlobbing: false,
  102. usePolling: false,
  103. interval: 100,
  104. binaryInterval: 300,
  105. alwaysStat: false,
  106. depth: 99,
  107. awaitWriteFinish: {
  108. stabilityThreshold: 2000,
  109. pollInterval: 100
  110. },
  111. ignorePermissionErrors: false,
  112. atomic: true // or a custom 'atomicity delay', in milliseconds (default 100)
  113. });
  114. ```
  115. `chokidar.watch(paths, [options])`
  116. * `paths` (string or array of strings). Paths to files, dirs to be watched
  117. recursively, or glob patterns.
  118. - Note: globs must not contain windows separators (`\`),
  119. because that's how they work by the standard —
  120. you'll need to replace them with forward slashes (`/`).
  121. - Note 2: for additional glob documentation, check out low-level
  122. library: [picomatch](https://github.com/micromatch/picomatch).
  123. * `options` (object) Options object as defined below:
  124. #### Persistence
  125. * `persistent` (default: `true`). Indicates whether the process
  126. should continue to run as long as files are being watched. If set to
  127. `false` when using `fsevents` to watch, no more events will be emitted
  128. after `ready`, even if the process continues to run.
  129. #### Path filtering
  130. * `ignored` ([anymatch](https://github.com/es128/anymatch)-compatible definition)
  131. Defines files/paths to be ignored. The whole relative or absolute path is
  132. tested, not just filename. If a function with two arguments is provided, it
  133. gets called twice per path - once with a single argument (the path), second
  134. time with two arguments (the path and the
  135. [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats)
  136. object of that path).
  137. * `ignoreInitial` (default: `false`). If set to `false` then `add`/`addDir` events are also emitted for matching paths while
  138. instantiating the watching as chokidar discovers these file paths (before the `ready` event).
  139. * `followSymlinks` (default: `true`). When `false`, only the
  140. symlinks themselves will be watched for changes instead of following
  141. the link references and bubbling events through the link's path.
  142. * `cwd` (no default). The base directory from which watch `paths` are to be
  143. derived. Paths emitted with events will be relative to this.
  144. * `disableGlobbing` (default: `false`). If set to `true` then the strings passed to `.watch()` and `.add()` are treated as
  145. literal path names, even if they look like globs.
  146. #### Performance
  147. * `usePolling` (default: `false`).
  148. Whether to use fs.watchFile (backed by polling), or fs.watch. If polling
  149. leads to high CPU utilization, consider setting this to `false`. It is
  150. typically necessary to **set this to `true` to successfully watch files over
  151. a network**, and it may be necessary to successfully watch files in other
  152. non-standard situations. Setting to `true` explicitly on MacOS overrides the
  153. `useFsEvents` default. You may also set the CHOKIDAR_USEPOLLING env variable
  154. to true (1) or false (0) in order to override this option.
  155. * _Polling-specific settings_ (effective when `usePolling: true`)
  156. * `interval` (default: `100`). Interval of file system polling, in milliseconds. You may also
  157. set the CHOKIDAR_INTERVAL env variable to override this option.
  158. * `binaryInterval` (default: `300`). Interval of file system
  159. polling for binary files.
  160. ([see list of binary extensions](https://github.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
  161. * `useFsEvents` (default: `true` on MacOS). Whether to use the
  162. `fsevents` watching interface if available. When set to `true` explicitly
  163. and `fsevents` is available this supercedes the `usePolling` setting. When
  164. set to `false` on MacOS, `usePolling: true` becomes the default.
  165. * `alwaysStat` (default: `false`). If relying upon the
  166. [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats)
  167. object that may get passed with `add`, `addDir`, and `change` events, set
  168. this to `true` to ensure it is provided even in cases where it wasn't
  169. already available from the underlying watch events.
  170. * `depth` (default: `undefined`). If set, limits how many levels of
  171. subdirectories will be traversed.
  172. * `awaitWriteFinish` (default: `false`).
  173. By default, the `add` event will fire when a file first appears on disk, before
  174. the entire file has been written. Furthermore, in some cases some `change`
  175. events will be emitted while the file is being written. In some cases,
  176. especially when watching for large files there will be a need to wait for the
  177. write operation to finish before responding to a file creation or modification.
  178. Setting `awaitWriteFinish` to `true` (or a truthy value) will poll file size,
  179. holding its `add` and `change` events until the size does not change for a
  180. configurable amount of time. The appropriate duration setting is heavily
  181. dependent on the OS and hardware. For accurate detection this parameter should
  182. be relatively high, making file watching much less responsive.
  183. Use with caution.
  184. * *`options.awaitWriteFinish` can be set to an object in order to adjust
  185. timing params:*
  186. * `awaitWriteFinish.stabilityThreshold` (default: 2000). Amount of time in
  187. milliseconds for a file size to remain constant before emitting its event.
  188. * `awaitWriteFinish.pollInterval` (default: 100). File size polling interval, in milliseconds.
  189. #### Errors
  190. * `ignorePermissionErrors` (default: `false`). Indicates whether to watch files
  191. that don't have read permissions if possible. If watching fails due to `EPERM`
  192. or `EACCES` with this set to `true`, the errors will be suppressed silently.
  193. * `atomic` (default: `true` if `useFsEvents` and `usePolling` are `false`).
  194. Automatically filters out artifacts that occur when using editors that use
  195. "atomic writes" instead of writing directly to the source file. If a file is
  196. re-added within 100 ms of being deleted, Chokidar emits a `change` event
  197. rather than `unlink` then `add`. If the default of 100 ms does not work well
  198. for you, you can override it by setting `atomic` to a custom value, in
  199. milliseconds.
  200. ### Methods & Events
  201. `chokidar.watch()` produces an instance of `FSWatcher`. Methods of `FSWatcher`:
  202. * `.add(path / paths)`: Add files, directories, or glob patterns for tracking.
  203. Takes an array of strings or just one string.
  204. * `.on(event, callback)`: Listen for an FS event.
  205. Available events: `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `ready`,
  206. `raw`, `error`.
  207. Additionally `all` is available which gets emitted with the underlying event
  208. name and path for every event other than `ready`, `raw`, and `error`. `raw` is internal, use it carefully.
  209. * `.unwatch(path / paths)`: Stop watching files, directories, or glob patterns.
  210. Takes an array of strings or just one string.
  211. * `.close()`: **async** Removes all listeners from watched files. Asynchronous, returns Promise. Use with `await` to ensure bugs don't happen.
  212. * `.getWatched()`: Returns an object representing all the paths on the file
  213. system being watched by this `FSWatcher` instance. The object's keys are all the
  214. directories (using absolute paths unless the `cwd` option was used), and the
  215. values are arrays of the names of the items contained in each directory.
  216. ## CLI
  217. If you need a CLI interface for your file watching, check out
  218. [chokidar-cli](https://github.com/open-cli-tools/chokidar-cli), allowing you to
  219. execute a command on each change, or get a stdio stream of change events.
  220. ## Install Troubleshooting
  221. * `npm WARN optional dep failed, continuing fsevents@n.n.n`
  222. * This message is normal part of how `npm` handles optional dependencies and is
  223. not indicative of a problem. Even if accompanied by other related error messages,
  224. Chokidar should function properly.
  225. * `TypeError: fsevents is not a constructor`
  226. * Update chokidar by doing `rm -rf node_modules package-lock.json yarn.lock && npm install`, or update your dependency that uses chokidar.
  227. * Chokidar is producing `ENOSP` error on Linux, like this:
  228. * `bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell`
  229. `Error: watch /home/ ENOSPC`
  230. * This means Chokidar ran out of file handles and you'll need to increase their count by executing the following command in Terminal:
  231. `echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p`
  232. ## Changelog
  233. For more detailed changelog, see [`full_changelog.md`](.github/full_changelog.md).
  234. - **v3.5 (Jan 6, 2021):** Support for ARM Macs with Apple Silicon. Fixes for deleted symlinks.
  235. - **v3.4 (Apr 26, 2020):** Support for directory-based symlinks. Fixes for macos file replacement.
  236. - **v3.3 (Nov 2, 2019):** `FSWatcher#close()` method became async. That fixes IO race conditions related to close method.
  237. - **v3.2 (Oct 1, 2019):** Improve Linux RAM usage by 50%. Race condition fixes. Windows glob fixes. Improve stability by using tight range of dependency versions.
  238. - **v3.1 (Sep 16, 2019):** dotfiles are no longer filtered out by default. Use `ignored` option if needed. Improve initial Linux scan time by 50%.
  239. - **v3 (Apr 30, 2019):** massive CPU & RAM consumption improvements; reduces deps / package size by a factor of 17x and bumps Node.js requirement to v8.16 and higher.
  240. - **v2 (Dec 29, 2017):** Globs are now posix-style-only; without windows support. Tons of bugfixes.
  241. - **v1 (Apr 7, 2015):** Glob support, symlink support, tons of bugfixes. Node 0.8+ is supported
  242. - **v0.1 (Apr 20, 2012):** Initial release, extracted from [Brunch](https://github.com/brunch/brunch/blob/9847a065aea300da99bd0753f90354cde9de1261/src/helpers.coffee#L66)
  243. ## Also
  244. Why was chokidar named this way? What's the meaning behind it?
  245. >Chowkidar is a transliteration of a Hindi word meaning 'watchman, gatekeeper', चौकीदार. This ultimately comes from Sanskrit _ चतुष्क_ (crossway, quadrangle, consisting-of-four).
  246. ## License
  247. MIT (c) Paul Miller (<https://paulmillr.com>), see [LICENSE](LICENSE) file.