chokidar README

项目的 README,来自 github.com/paulmillr/chokidar。合并为一个 markdown 文件:README.md。

Chokidar Weekly downloads

Minimal and efficient cross-platform file watching library

Why?

Raw fs.watch / fs.watchFile are useless: fs.watch reports many changes as an non-transparent rename, can fire twice for one change, and recursive watching differs across platforms. Chokidar normalizes all of that:

Chokidar watches everything under the paths you give it, so scope them (and use ignored / depth) rather than watching more than you need.

Made for Brunch in 2012, it is now used in 30+ million projects and has proven itself in production environments. The current major is v6 (Oct 2026) - with lots of major improvements.

Getting started

npm install chokidar
import chokidar from 'chokidar';
// or: import { watch } from 'chokidar';
// or: const chokidar = require('chokidar');

chokidar.watch('src').on('all', (event, path) => console.log(event, path));

A fuller example:

import chokidar from 'chokidar';

const watcher = chokidar.watch('src', {
  // strings are exact paths (not globs), regexes test the whole path, functions get (path, stats?)
  ignored: [
    /(^|\/)\../, // dotfiles
    (path, stats) => stats?.isFile() && !path.endsWith('.js'), // only .js files
  ],
  ignoreInitial: true, // don't emit add/addDir for files that already exist
});

watcher
  .on('add', (path, stats) => console.log('added', path, stats?.size))
  .on('change', (path) => console.log('changed', path))
  .on('unlink', (path) => console.log('removed', path))
  .on('ready', () => console.log('initial scan done'))
  .on('error', (err) => console.error(err));

watcher.add(['lib', 'index.js']); // add more paths later
watcher.unwatch('lib'); // synchronous
console.log(watcher.getWatched()); // { '/abs': ['src'], '/abs/src': ['a.js', 'sub'], ... }
await watcher.close(); // async and terminal: create a new watcher to resume

Recipes:

// Large or chunked writes, and editors that save via temp file + rename
chokidar.watch('uploads', {
  awaitWriteFinish: { stabilityThreshold: 2000, pollInterval: 100 }, // wait for size to settle
  atomic: 100, // unlink + add within 100 ms becomes one change
});

// Network or otherwise unusual filesystems where fs.watch is unreliable
chokidar.watch('/mnt/nfs/data', { backend: 'polling', pollingInterval: 500 });

API

chokidar.watch(paths, [options]) returns an FSWatcher. paths is a string or an array of strings; files are watched, directories are watched recursively. All options with their defaults:

chokidar.watch('dir-or-file', {
  // Filtering
  ignored: undefined, // matcher or array of matchers, see below
  ignoreInitial: false,
  followSymlinks: true,
  cwd: undefined,
  depth: undefined, // unlimited
  // Backend
  backend: 'auto', // 'auto' | 'native' | 'native-recursive' | 'polling'
  pollingInterval: 100, // polling backend only
  pollingBinaryInterval: 300, // polling backend only
  // Event timing
  atomic: true, // false with backend: 'polling'; or a number of ms
  awaitWriteFinish: false, // or true, or { stabilityThreshold: 2000, pollInterval: 100 }
  alwaysStat: false,
  // Errors and lifecycle
  ignorePermissionErrors: false,
  persistent: true,
});

Filtering

Backend

Event timing

Errors and lifecycle

Methods

Events

Event Listener arguments
add, addDir, change (path, stats?); stats when available, always with alwaysStat
unlink, unlinkDir (path)
all (event, path, stats?) for each of the five events above
ready none; the initial scan is complete
error (error)
raw (event, path, details) from the backend; unstable, use with care

Troubleshooting

Changelog

Upgrading

Version 6 requires Node.js 22.22 or newer. An FSWatcher cannot be reopened after .close() starts; construct a new watcher instead. Polling now defaults atomic to false, while an explicit atomic value is preserved. Use pollingInterval and pollingBinaryInterval for polling configuration; the v5 interval and binaryInterval spellings remain as deprecated aliases.

Globs were removed in v4. To replicate them:

// v3
chokidar.watch('**/*.js');
chokidar.watch('./directory/**/*');

// v4+: filter instead
chokidar.watch('.', {
  ignored: (path, stats) => stats?.isFile() && !path.endsWith('.js'), // only watch js files
});
chokidar.watch('./directory');

// or expand the glob yourself
import { glob } from 'node:fs/promises';
const watcher = chokidar.watch(await Array.fromAsync(glob('**/*.js')));

// unwatching
watcher.unwatch('**/*.js'); // v3
watcher.unwatch(await Array.fromAsync(glob('**/*.js'))); // v4+

Contributing

Run npm ci && npm run build && npm test (tests import the built files, so build first). Internals and design requirements are documented in docs/architecture.md; the cross-platform CI setup is in docs/vm-testing.md.

Also

Why was chokidar named this way? What's the meaning behind it?

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.

License

MIT (c) Paul Miller (https://paulmillr.com), see LICENSE file.

chokidar (paulmillr/chokidar)

正在搜索数据库…

这是什么?Chokidar 是一个精简、高效的跨平台文件监听库,适用于 Node.js。它能把操作系统原生文件系统 API 产生的杂乱事件,统一整理成清晰的 add、change 和 unlink 事件。
这是我要导入的库,还是自带命令行工具?它是通过 npm 安装、在代码中调用 chokidar.watch() 使用的 Node.js 库。如果你想要命令行工具,可以使用单独的第三方包 chokidar-cli,但它不属于核心包的一部分。
我该怎么开始监听文件?先用 npm 安装,然后调用 chokidar.watch(paths, [options]),传入一个路径或路径数组,再使用 .on(event, callback) 监听事件(如 add、change、unlink 等)。
它依赖什么?它基于 Node 的核心模块 fs 构建。从 v4 开始,它只剩一个外部依赖(readdirp),而较早版本有 13 个。
它还支持像 watch('*.js') 这样的 glob 通配符模式吗?不支持了。glob 支持在 v4 中随内置的 fsevents 二进制文件一起被移除,所以现在你需要在传入路径之前,自行展开所有 glob 模式。
它在 macOS、Linux 和 Windows 上的表现一样吗?基本一样。但 macOS 通过原生的 fsevents 后端能获得更丰富的事件(直接报告文件名)。对于网络驱动器等特殊情况,你可能需要强制使用 usePolling,而不是依赖原生的 fs.watch。
为什么叫 chokidar?它的名字源自印地语/乌尔都语单词 'chowkidar'(चौकीदार),意为守望者或门卫。这个词可以追溯到梵语中的“十字路口”一词。
最新的 v5 版本有什么变化?v5 于 2025 年 11 月发布,它把该包改为仅支持 ESM,并将最低支持的 Node.js 版本提高到 v20。
它能处理分块写入的文件,或编辑器原子方式保存的文件吗?可以。awaitWriteFinish 会轮询文件大小,直到写入停止,以处理分块保存;atomic 选项默认开启,会把某些编辑器使用的“先删除再重建”模式合并为一次 change 事件。
chokidar 实际上有多广泛的使用?它最初是 2012 年从 Brunch 构建工具中提取出来的,现在大约有 3000 万个代码仓库在使用它。
有哪些类似的项目?tsx, core-js, upm, Inquirer.js, ua-parser-js, joi, node, tsdx
作者
paulmillr
大小
2.1 MB
星标
12.3K
时长
14年
提交 · 90 天