{"id":716,"url":"https://github.com/paulmillr/chokidar","last_synced_at":"2025-05-12T16:12:54.965Z","repository":{"id":3067513,"uuid":"4090287","full_name":"paulmillr/chokidar","owner":"paulmillr","description":"Minimal and efficient cross-platform file watching library","archived":false,"fork":false,"pushed_at":"2025-05-01T13:07:26.000Z","size":2039,"stargazers_count":11377,"open_issues_count":29,"forks_count":597,"subscribers_count":86,"default_branch":"main","last_synced_at":"2025-05-05T14:10:35.081Z","etag":null,"topics":["chokidar","filesystem","fsevents","nodejs","watch-files","watcher"],"latest_commit_sha":null,"homepage":"https://paulmillr.com","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/paulmillr.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/funding.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"paulmillr"}},"created_at":"2012-04-20T19:17:49.000Z","updated_at":"2025-05-05T03:13:18.000Z","dependencies_parsed_at":"2025-01-06T12:23:54.529Z","dependency_job_id":"73a81315-ab7a-4f99-ab03-ee9b38436cb6","html_url":"https://github.com/paulmillr/chokidar","commit_stats":{"total_commits":1496,"total_committers":122,"mean_commits":"12.262295081967213","dds":0.5280748663101604,"last_synced_commit":"97894d36657c8e4571bd1a07fb6e2a3f50f7019d"},"previous_names":[],"tags_count":103,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paulmillr%2Fchokidar","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paulmillr%2Fchokidar/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paulmillr%2Fchokidar/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paulmillr%2Fchokidar/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/paulmillr","download_url":"https://codeload.github.com/paulmillr/chokidar/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252551983,"owners_count":21766617,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["chokidar","filesystem","fsevents","nodejs","watch-files","watcher"],"created_at":"2024-01-05T20:15:29.540Z","updated_at":"2025-05-12T16:12:54.922Z","avatar_url":"https://github.com/paulmillr.png","language":"TypeScript","funding_links":["https://github.com/sponsors/paulmillr"],"categories":["JavaScript","Node","命令行","目录","[Node.js](http://nodejs.org/) feature module and bundler","包","TypeScript","Repository","Packages","Utilities","GIT 仓库","Npm","HarmonyOS","others","NodeJS","文件","Filesystem","Uncategorized","Libraries","\u003e 10K ⭐️"],"sub_categories":["文件处理","redux 扩展","文件系统","Filesystem","React Components","macros","Windows Manager","Uncategorized"],"readme":"# Chokidar [![Weekly downloads](https://img.shields.io/npm/dw/chokidar.svg)](https://github.com/paulmillr/chokidar)\n\nMinimal and efficient cross-platform file watching library\n\n## Why?\n\nThere are many reasons to prefer Chokidar to raw fs.watch / fs.watchFile in 2025:\n\n- Events are properly reported\n  - macOS events report filenames\n  - events are not reported twice\n  - changes are reported as add / change / unlink instead of useless `rename`\n- Atomic writes are supported, using `atomic` option\n  - Some file editors use them\n- Chunked writes are supported, using `awaitWriteFinish` option\n  - Large files are commonly written in chunks\n- File / dir filtering is supported\n- Symbolic links are supported\n- Recursive watching is always supported, instead of partial when using raw events\n  - Includes a way to limit recursion depth\n\nChokidar relies on the Node.js core `fs` module, but when using\n`fs.watch` and `fs.watchFile` for watching, it normalizes the events it\nreceives, often checking for truth by getting file stats and/or dir contents.\nThe `fs.watch`-based implementation is the default, which\navoids polling and keeps CPU usage down. Be advised that chokidar will initiate\nwatchers recursively for everything within scope of the paths that have been\nspecified, so be judicious about not wasting system resources by watching much\nmore than needed. For some cases, `fs.watchFile`, which utilizes polling and uses more resources, is used.\n\nMade for [Brunch](https://brunch.io/) in 2012,\nit is now used in [~30 million repositories](https://www.npmjs.com/browse/depended/chokidar) and\nhas proven itself in production environments.\n\n**Sep 2024 update:** v4 is out! It decreases dependency count from 13 to 1, removes\nsupport for globs, adds support for ESM / Common.js modules, and bumps minimum node.js version from v8 to v14.\nCheck out [upgrading](#upgrading).\n\n## Getting started\n\nInstall with npm:\n\n```sh\nnpm install chokidar\n```\n\nUse it in your code:\n\n```javascript\nimport chokidar from 'chokidar';\n\n// One-liner for current directory\nchokidar.watch('.').on('all', (event, path) =\u003e {\n  console.log(event, path);\n});\n\n// Extended options\n// ----------------\n\n// Initialize watcher.\nconst watcher = chokidar.watch('file, dir, or array', {\n  ignored: (path, stats) =\u003e stats?.isFile() \u0026\u0026 !path.endsWith('.js'), // only watch js files\n  persistent: true,\n});\n\n// Something to use when events are received.\nconst log = console.log.bind(console);\n// Add event listeners.\nwatcher\n  .on('add', (path) =\u003e log(`File ${path} has been added`))\n  .on('change', (path) =\u003e log(`File ${path} has been changed`))\n  .on('unlink', (path) =\u003e log(`File ${path} has been removed`));\n\n// More possible events.\nwatcher\n  .on('addDir', (path) =\u003e log(`Directory ${path} has been added`))\n  .on('unlinkDir', (path) =\u003e log(`Directory ${path} has been removed`))\n  .on('error', (error) =\u003e log(`Watcher error: ${error}`))\n  .on('ready', () =\u003e log('Initial scan complete. Ready for changes'))\n  .on('raw', (event, path, details) =\u003e {\n    // internal\n    log('Raw event info:', event, path, details);\n  });\n\n// 'add', 'addDir' and 'change' events also receive stat() results as second\n// argument when available: https://nodejs.org/api/fs.html#fs_class_fs_stats\nwatcher.on('change', (path, stats) =\u003e {\n  if (stats) console.log(`File ${path} changed size to ${stats.size}`);\n});\n\n// Watch new files.\nwatcher.add('new-file');\nwatcher.add(['new-file-2', 'new-file-3']);\n\n// Get list of actual paths being watched on the filesystem\nlet watchedPaths = watcher.getWatched();\n\n// Un-watch some files.\nawait watcher.unwatch('new-file');\n\n// Stop watching. The method is async!\nawait watcher.close().then(() =\u003e console.log('closed'));\n\n// Full list of options. See below for descriptions.\n// Do not use this example!\nchokidar.watch('file', {\n  persistent: true,\n\n  // ignore .txt files\n  ignored: (file) =\u003e file.endsWith('.txt'),\n  // watch only .txt files\n  // ignored: (file, _stats) =\u003e _stats?.isFile() \u0026\u0026 !file.endsWith('.txt'),\n\n  awaitWriteFinish: true, // emit single event when chunked writes are completed\n  atomic: true, // emit proper events when \"atomic writes\" (mv _tmp file) are used\n\n  // The options also allow specifying custom intervals in ms\n  // awaitWriteFinish: {\n  //   stabilityThreshold: 2000,\n  //   pollInterval: 100\n  // },\n  // atomic: 100,\n\n  interval: 100,\n  binaryInterval: 300,\n\n  cwd: '.',\n  depth: 99,\n\n  followSymlinks: true,\n  ignoreInitial: false,\n  ignorePermissionErrors: false,\n  usePolling: false,\n  alwaysStat: false,\n});\n```\n\n`chokidar.watch(paths, [options])`\n\n- `paths` (string or array of strings). Paths to files, dirs to be watched\n  recursively.\n- `options` (object) Options object as defined below:\n\n#### Persistence\n\n- `persistent` (default: `true`). Indicates whether the process\n  should continue to run as long as files are being watched.\n\n#### Path filtering\n\n- `ignored` function, regex, or path. Defines files/paths to be ignored.\n  The whole relative or absolute path is tested, not just filename. If a function with two arguments\n  is provided, it gets called twice per path - once with a single argument (the path), second\n  time with two arguments (the path and the\n  [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats)\n  object of that path).\n- `ignoreInitial` (default: `false`). If set to `false` then `add`/`addDir` events are also emitted for matching paths while\n  instantiating the watching as chokidar discovers these file paths (before the `ready` event).\n- `followSymlinks` (default: `true`). When `false`, only the\n  symlinks themselves will be watched for changes instead of following\n  the link references and bubbling events through the link's path.\n- `cwd` (no default). The base directory from which watch `paths` are to be\n  derived. Paths emitted with events will be relative to this.\n\n#### Performance\n\n- `usePolling` (default: `false`).\n  Whether to use fs.watchFile (backed by polling), or fs.watch. If polling\n  leads to high CPU utilization, consider setting this to `false`. It is\n  typically necessary to **set this to `true` to successfully watch files over\n  a network**, and it may be necessary to successfully watch files in other\n  non-standard situations. Setting to `true` explicitly on MacOS overrides the\n  `useFsEvents` default. You may also set the CHOKIDAR_USEPOLLING env variable\n  to true (1) or false (0) in order to override this option.\n- _Polling-specific settings_ (effective when `usePolling: true`)\n  - `interval` (default: `100`). Interval of file system polling, in milliseconds. You may also\n    set the CHOKIDAR_INTERVAL env variable to override this option.\n  - `binaryInterval` (default: `300`). Interval of file system\n    polling for binary files.\n    ([see list of binary extensions](https://github.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))\n- `alwaysStat` (default: `false`). If relying upon the\n  [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats)\n  object that may get passed with `add`, `addDir`, and `change` events, set\n  this to `true` to ensure it is provided even in cases where it wasn't\n  already available from the underlying watch events.\n- `depth` (default: `undefined`). If set, limits how many levels of\n  subdirectories will be traversed.\n- `awaitWriteFinish` (default: `false`).\n  By default, the `add` event will fire when a file first appears on disk, before\n  the entire file has been written. Furthermore, in some cases some `change`\n  events will be emitted while the file is being written. In some cases,\n  especially when watching for large files there will be a need to wait for the\n  write operation to finish before responding to a file creation or modification.\n  Setting `awaitWriteFinish` to `true` (or a truthy value) will poll file size,\n  holding its `add` and `change` events until the size does not change for a\n  configurable amount of time. The appropriate duration setting is heavily\n  dependent on the OS and hardware. For accurate detection this parameter should\n  be relatively high, making file watching much less responsive.\n  Use with caution.\n  - _`options.awaitWriteFinish` can be set to an object in order to adjust\n    timing params:_\n  - `awaitWriteFinish.stabilityThreshold` (default: 2000). Amount of time in\n    milliseconds for a file size to remain constant before emitting its event.\n  - `awaitWriteFinish.pollInterval` (default: 100). File size polling interval, in milliseconds.\n\n#### Errors\n\n- `ignorePermissionErrors` (default: `false`). Indicates whether to watch files\n  that don't have read permissions if possible. If watching fails due to `EPERM`\n  or `EACCES` with this set to `true`, the errors will be suppressed silently.\n- `atomic` (default: `true` if `useFsEvents` and `usePolling` are `false`).\n  Automatically filters out artifacts that occur when using editors that use\n  \"atomic writes\" instead of writing directly to the source file. If a file is\n  re-added within 100 ms of being deleted, Chokidar emits a `change` event\n  rather than `unlink` then `add`. If the default of 100 ms does not work well\n  for you, you can override it by setting `atomic` to a custom value, in\n  milliseconds.\n\n### Methods \u0026 Events\n\n`chokidar.watch()` produces an instance of `FSWatcher`. Methods of `FSWatcher`:\n\n- `.add(path / paths)`: Add files, directories for tracking.\n  Takes an array of strings or just one string.\n- `.on(event, callback)`: Listen for an FS event.\n  Available events: `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `ready`,\n  `raw`, `error`.\n  Additionally `all` is available which gets emitted with the underlying event\n  name and path for every event other than `ready`, `raw`, and `error`. `raw` is internal, use it carefully.\n- `.unwatch(path / paths)`: Stop watching files or directories.\n  Takes an array of strings or just one string.\n- `.close()`: **async** Removes all listeners from watched files. Asynchronous, returns Promise. Use with `await` to ensure bugs don't happen.\n- `.getWatched()`: Returns an object representing all the paths on the file\n  system being watched by this `FSWatcher` instance. The object's keys are all the\n  directories (using absolute paths unless the `cwd` option was used), and the\n  values are arrays of the names of the items contained in each directory.\n\n### CLI\n\nCheck out third party [chokidar-cli](https://github.com/open-cli-tools/chokidar-cli),\nwhich allows to execute a command on each change, or get a stdio stream of change events.\n\n## Troubleshooting\n\nSometimes, Chokidar runs out of file handles, causing `EMFILE` and `ENOSP` errors:\n\n- `bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell`\n- `Error: watch /home/ ENOSPC`\n\nThere are two things that can cause it.\n\n1. Exhausted file handles for generic fs operations\n   - Can be solved by using [graceful-fs](https://www.npmjs.com/package/graceful-fs),\n     which can monkey-patch native `fs` module used by chokidar: `let fs = require('fs'); let grfs = require('graceful-fs'); grfs.gracefulify(fs);`\n   - Can also be solved by tuning OS: `echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf \u0026\u0026 sudo sysctl -p`.\n2. Exhausted file handles for `fs.watch`\n   - Can't seem to be solved by graceful-fs or OS tuning\n   - It's possible to start using `usePolling: true`, which will switch backend to resource-intensive `fs.watchFile`\n\nAll fsevents-related issues (`WARN optional dep failed`, `fsevents is not a constructor`) are solved by upgrading to v4+.\n\n## Changelog\n\n- **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+\n- **v3 (Apr 2019):** massive CPU \u0026 RAM consumption improvements; reduces deps / package size by a factor of 17x and bumps Node.js requirement to v8.16+.\n- **v2 (Dec 2017):** globs are now posix-style-only. Tons of bugfixes.\n- **v1 (Apr 2015):** glob support, symlink support, tons of bugfixes. Node 0.8+ is supported\n- **v0.1 (Apr 2012):** Initial release, extracted from [Brunch](https://github.com/brunch/brunch/blob/9847a065aea300da99bd0753f90354cde9de1261/src/helpers.coffee#L66)\n\n### Upgrading\n\nIf you've used globs before and want do replicate the functionality with v4:\n\n```js\n// v3\nchok.watch('**/*.js');\nchok.watch('./directory/**/*');\n\n// v4\nchok.watch('.', {\n  ignored: (path, stats) =\u003e stats?.isFile() \u0026\u0026 !path.endsWith('.js'), // only watch js files\n});\nchok.watch('./directory');\n\n// other way\nimport { glob } from 'node:fs/promises';\nconst watcher = watch(await Array.fromAsync(glob('**/*.js')));\n\n// unwatching\n// v3\nchok.unwatch('**/*.js');\n// v4\nchok.unwatch(await glob('**/*.js'));\n```\n\n## Also\n\nWhy was chokidar named this way? What's the meaning behind it?\n\n\u003e 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.\n\n## License\n\nMIT (c) Paul Miller (\u003chttps://paulmillr.com\u003e), see [LICENSE](LICENSE) file.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpaulmillr%2Fchokidar","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpaulmillr%2Fchokidar","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpaulmillr%2Fchokidar/lists"}