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.

294 lines
13 KiB

4 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) [![Mac/Linux Build Status](https://img.shields.io/travis/paulmillr/chokidar/master.svg?label=Mac%20OSX%20%26%20Linux)](https://travis-ci.org/paulmillr/chokidar) [![Windows Build status](https://img.shields.io/appveyor/ci/paulmillr/chokidar/master.svg?label=Windows)](https://ci.appveyor.com/project/paulmillr/chokidar/branch/master) [![Coverage Status](https://coveralls.io/repos/paulmillr/chokidar/badge.svg)](https://coveralls.io/r/paulmillr/chokidar)
  2. > A neat wrapper around node.js fs.watch / fs.watchFile / FSEvents.
  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. * Has [a lot of other issues](https://github.com/nodejs/node/search?q=fs.watch&type=Issues)
  11. * Does not provide an easy way to recursively watch file trees.
  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](http://brunch.io)** (an ultra-swift web app build tool), it is now used in
  18. [gulp](https://github.com/gulpjs/gulp/),
  19. [karma](http://karma-runner.github.io),
  20. [PM2](https://github.com/Unitech/PM2),
  21. [browserify](http://browserify.org/),
  22. [webpack](http://webpack.github.io/),
  23. [BrowserSync](http://www.browsersync.io/),
  24. [Microsoft's Visual Studio Code](https://github.com/microsoft/vscode),
  25. and [many others](https://www.npmjs.org/browse/depended/chokidar/).
  26. It has proven itself in production environments.
  27. ## How?
  28. Chokidar does still rely on the Node.js core `fs` module, but when using
  29. `fs.watch` and `fs.watchFile` for watching, it normalizes the events it
  30. receives, often checking for truth by getting file stats and/or dir contents.
  31. On MacOS, chokidar by default uses a native extension exposing the Darwin
  32. `FSEvents` API. This provides very efficient recursive watching compared with
  33. implementations like `kqueue` available on most \*nix platforms. Chokidar still
  34. does have to do some work to normalize the events received that way as well.
  35. On other platforms, the `fs.watch`-based implementation is the default, which
  36. avoids polling and keeps CPU usage down. Be advised that chokidar will initiate
  37. watchers recursively for everything within scope of the paths that have been
  38. specified, so be judicious about not wasting system resources by watching much
  39. more than needed.
  40. ## Getting started
  41. Install with npm:
  42. ```sh
  43. npm install chokidar
  44. ```
  45. Then `require` and use it in your code:
  46. ```javascript
  47. var chokidar = require('chokidar');
  48. // One-liner for current directory, ignores .dotfiles
  49. chokidar.watch('.', {ignored: /(^|[\/\\])\../}).on('all', (event, path) => {
  50. console.log(event, path);
  51. });
  52. ```
  53. ```javascript
  54. // Example of a more typical implementation structure:
  55. // Initialize watcher.
  56. var watcher = chokidar.watch('file, dir, glob, or array', {
  57. ignored: /(^|[\/\\])\../,
  58. persistent: true
  59. });
  60. // Something to use when events are received.
  61. var log = console.log.bind(console);
  62. // Add event listeners.
  63. watcher
  64. .on('add', path => log(`File ${path} has been added`))
  65. .on('change', path => log(`File ${path} has been changed`))
  66. .on('unlink', path => log(`File ${path} has been removed`));
  67. // More possible events.
  68. watcher
  69. .on('addDir', path => log(`Directory ${path} has been added`))
  70. .on('unlinkDir', path => log(`Directory ${path} has been removed`))
  71. .on('error', error => log(`Watcher error: ${error}`))
  72. .on('ready', () => log('Initial scan complete. Ready for changes'))
  73. .on('raw', (event, path, details) => {
  74. log('Raw event info:', event, path, details);
  75. });
  76. // 'add', 'addDir' and 'change' events also receive stat() results as second
  77. // argument when available: http://nodejs.org/api/fs.html#fs_class_fs_stats
  78. watcher.on('change', (path, stats) => {
  79. if (stats) console.log(`File ${path} changed size to ${stats.size}`);
  80. });
  81. // Watch new files.
  82. watcher.add('new-file');
  83. watcher.add(['new-file-2', 'new-file-3', '**/other-file*']);
  84. // Get list of actual paths being watched on the filesystem
  85. var watchedPaths = watcher.getWatched();
  86. // Un-watch some files.
  87. watcher.unwatch('new-file*');
  88. // Stop watching.
  89. watcher.close();
  90. // Full list of options. See below for descriptions. (do not use this example)
  91. chokidar.watch('file', {
  92. persistent: true,
  93. ignored: '*.txt',
  94. ignoreInitial: false,
  95. followSymlinks: true,
  96. cwd: '.',
  97. disableGlobbing: false,
  98. usePolling: true,
  99. interval: 100,
  100. binaryInterval: 300,
  101. alwaysStat: false,
  102. depth: 99,
  103. awaitWriteFinish: {
  104. stabilityThreshold: 2000,
  105. pollInterval: 100
  106. },
  107. ignorePermissionErrors: false,
  108. atomic: true // or a custom 'atomicity delay', in milliseconds (default 100)
  109. });
  110. ```
  111. ## API
  112. `chokidar.watch(paths, [options])`
  113. * `paths` (string or array of strings). Paths to files, dirs to be watched
  114. recursively, or glob patterns.
  115. * `options` (object) Options object as defined below:
  116. #### Persistence
  117. * `persistent` (default: `true`). Indicates whether the process
  118. should continue to run as long as files are being watched. If set to
  119. `false` when using `fsevents` to watch, no more events will be emitted
  120. after `ready`, even if the process continues to run.
  121. #### Path filtering
  122. * `ignored` ([anymatch](https://github.com/es128/anymatch)-compatible definition)
  123. Defines files/paths to be ignored. The whole relative or absolute path is
  124. tested, not just filename. If a function with two arguments is provided, it
  125. gets called twice per path - once with a single argument (the path), second
  126. time with two arguments (the path and the
  127. [`fs.Stats`](http://nodejs.org/api/fs.html#fs_class_fs_stats)
  128. object of that path).
  129. * `ignoreInitial` (default: `false`). If set to `false` then `add`/`addDir` events are also emitted for matching paths while
  130. instantiating the watching as chokidar discovers these file paths (before the `ready` event).
  131. * `followSymlinks` (default: `true`). When `false`, only the
  132. symlinks themselves will be watched for changes instead of following
  133. the link references and bubbling events through the link's path.
  134. * `cwd` (no default). The base directory from which watch `paths` are to be
  135. derived. Paths emitted with events will be relative to this.
  136. * `disableGlobbing` (default: `false`). If set to `true` then the strings passed to `.watch()` and `.add()` are treated as
  137. literal path names, even if they look like globs.
  138. #### Performance
  139. * `usePolling` (default: `false`).
  140. Whether to use fs.watchFile (backed by polling), or fs.watch. If polling
  141. leads to high CPU utilization, consider setting this to `false`. It is
  142. typically necessary to **set this to `true` to successfully watch files over
  143. a network**, and it may be necessary to successfully watch files in other
  144. non-standard situations. Setting to `true` explicitly on MacOS overrides the
  145. `useFsEvents` default. You may also set the CHOKIDAR_USEPOLLING env variable
  146. to true (1) or false (0) in order to override this option.
  147. * _Polling-specific settings_ (effective when `usePolling: true`)
  148. * `interval` (default: `100`). Interval of file system polling. You may also
  149. set the CHOKIDAR_INTERVAL env variable to override this option.
  150. * `binaryInterval` (default: `300`). Interval of file system
  151. polling for binary files.
  152. ([see list of binary extensions](https://github.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
  153. * `useFsEvents` (default: `true` on MacOS). Whether to use the
  154. `fsevents` watching interface if available. When set to `true` explicitly
  155. and `fsevents` is available this supercedes the `usePolling` setting. When
  156. set to `false` on MacOS, `usePolling: true` becomes the default.
  157. * `alwaysStat` (default: `false`). If relying upon the
  158. [`fs.Stats`](http://nodejs.org/api/fs.html#fs_class_fs_stats)
  159. object that may get passed with `add`, `addDir`, and `change` events, set
  160. this to `true` to ensure it is provided even in cases where it wasn't
  161. already available from the underlying watch events.
  162. * `depth` (default: `undefined`). If set, limits how many levels of
  163. subdirectories will be traversed.
  164. * `awaitWriteFinish` (default: `false`).
  165. By default, the `add` event will fire when a file first appears on disk, before
  166. the entire file has been written. Furthermore, in some cases some `change`
  167. events will be emitted while the file is being written. In some cases,
  168. especially when watching for large files there will be a need to wait for the
  169. write operation to finish before responding to a file creation or modification.
  170. Setting `awaitWriteFinish` to `true` (or a truthy value) will poll file size,
  171. holding its `add` and `change` events until the size does not change for a
  172. configurable amount of time. The appropriate duration setting is heavily
  173. dependent on the OS and hardware. For accurate detection this parameter should
  174. be relatively high, making file watching much less responsive.
  175. Use with caution.
  176. * *`options.awaitWriteFinish` can be set to an object in order to adjust
  177. timing params:*
  178. * `awaitWriteFinish.stabilityThreshold` (default: 2000). Amount of time in
  179. milliseconds for a file size to remain constant before emitting its event.
  180. * `awaitWriteFinish.pollInterval` (default: 100). File size polling interval.
  181. #### Errors
  182. * `ignorePermissionErrors` (default: `false`). Indicates whether to watch files
  183. that don't have read permissions if possible. If watching fails due to `EPERM`
  184. or `EACCES` with this set to `true`, the errors will be suppressed silently.
  185. * `atomic` (default: `true` if `useFsEvents` and `usePolling` are `false`).
  186. Automatically filters out artifacts that occur when using editors that use
  187. "atomic writes" instead of writing directly to the source file. If a file is
  188. re-added within 100 ms of being deleted, Chokidar emits a `change` event
  189. rather than `unlink` then `add`. If the default of 100 ms does not work well
  190. for you, you can override it by setting `atomic` to a custom value, in
  191. milliseconds.
  192. ### Methods & Events
  193. `chokidar.watch()` produces an instance of `FSWatcher`. Methods of `FSWatcher`:
  194. * `.add(path / paths)`: Add files, directories, or glob patterns for tracking.
  195. Takes an array of strings or just one string.
  196. * `.on(event, callback)`: Listen for an FS event.
  197. Available events: `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `ready`,
  198. `raw`, `error`.
  199. Additionally `all` is available which gets emitted with the underlying event
  200. name and path for every event other than `ready`, `raw`, and `error`.
  201. * `.unwatch(path / paths)`: Stop watching files, directories, or glob patterns.
  202. Takes an array of strings or just one string.
  203. * `.close()`: Removes all listeners from watched files.
  204. * `.getWatched()`: Returns an object representing all the paths on the file
  205. system being watched by this `FSWatcher` instance. The object's keys are all the
  206. directories (using absolute paths unless the `cwd` option was used), and the
  207. values are arrays of the names of the items contained in each directory.
  208. ## CLI
  209. If you need a CLI interface for your file watching, check out
  210. [chokidar-cli](https://github.com/kimmobrunfeldt/chokidar-cli), allowing you to
  211. execute a command on each change, or get a stdio stream of change events.
  212. ## Install Troubleshooting
  213. * `npm WARN optional dep failed, continuing fsevents@n.n.n`
  214. * This message is normal part of how `npm` handles optional dependencies and is
  215. not indicative of a problem. Even if accompanied by other related error messages,
  216. Chokidar should function properly.
  217. * `ERR! stack Error: Python executable "python" is v3.4.1, which is not supported by gyp.`
  218. * You should be able to resolve this by installing python 2.7 and running:
  219. `npm config set python python2.7`
  220. * `gyp ERR! stack Error: not found: make`
  221. * On Mac, install the XCode command-line tools
  222. ## License
  223. The MIT License (MIT)
  224. Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com) & Elan Shanker
  225. Permission is hereby granted, free of charge, to any person obtaining a copy
  226. of this software and associated documentation files (the “Software”), to deal
  227. in the Software without restriction, including without limitation the rights
  228. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  229. copies of the Software, and to permit persons to whom the Software is
  230. furnished to do so, subject to the following conditions:
  231. The above copyright notice and this permission notice shall be included in
  232. all copies or substantial portions of the Software.
  233. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  234. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  235. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  236. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  237. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  238. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  239. THE SOFTWARE.