c96d0bed28c23abfae1d55dde2cf675649eaaa361ac37a0f204c31329fa3d02b1a6cb9e2b6e87dad1cd08e8c5c6a23d5af21a1b8b235ab7ddd05eac88674b8 13 KB

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