这些库都旨在解决 Node.js 原生 fs.watch 和 fs.watchFile 在不同操作系统上行为不一致的问题。它们提供了统一的事件接口(如 add, change, unlink),支持递归监听目录,并处理了底层文件系统的边缘情况。对于需要实时响应文件变动的工具(如构建系统、热重载服务器、同步工具),选择合适的监听库至关重要。
在 Node.js 生态中,监听文件系统变化是构建工具、开发服务器和同步脚本的核心需求。虽然 Node 原生提供了 fs.watch,但它在不同操作系统(Windows, macOS, Linux)上的行为差异巨大,且经常丢失事件。为了解决这些问题,社区涌现了多个封装库。本文将深入对比 chokidar, watchpack, node-watch 以及几个已逐渐退场的老牌库。
chokidar 是目前的行业标准。它在底层根据操作系统选择不同的策略:在 macOS 上使用 fsevents 原生绑定以获得高性能,在其他系统上回退到 fs.watch。它处理了原生 API 的许多边缘情况,比如目录重命名和原子写入。
// chokidar: 统一的事件接口
const chokidar = require('chokidar');
const watcher = chokidar.watch('src', {
ignored: /node_modules/,
persistent: true
});
watcher.on('change', path => console.log(`File ${path} has been changed`));
watchpack 是 Webpack 团队专门为构建工具设计的。它不直接暴露底层事件,而是关注“文件是否安全”和“目录时间戳”。它支持聚合事件,避免在大量文件同时变更时(如 git checkout)触发数千次回调。
// watchpack: 针对构建优化的监听
const Watchpack = require('watchpack');
const wp = new Watchpack({
aggregateTimeout: 1000
});
wp.watch([], ['src'], Date.now() - 10000);
wp.on('aggregated', (changes, removals) => {
console.log('Changes:', changes);
});
node-watch 坚持纯 JavaScript 实现,不依赖任何原生模块。这使得它在跨平台编译或某些 Serverless 环境中更具优势,尽管在 macOS 上性能可能略低于使用 fsevents 的方案。
// node-watch: 纯 JS 实现
const watch = require('node-watch');
watch('src', { recursive: true }, (evt, name) => {
console.log('%s changed.', name);
});
gaze, watch, filewatcher 属于早期生态。它们大多基于轮询(polling)或早期的 fs.watch 封装,缺乏对现代文件系统特性的支持。
// gaze: 旧式 API (已归档)
const gaze = require('gaze');
gaze('src/**/*', function(err, files) {
this.on('changed', function(file) {
console.log(file + ' was changed');
});
});
当监听包含数千文件的目录(如 node_modules)时,性能差异变得明显。
chokidar 性能优异,但在极端情况下(如监听整个磁盘根目录)仍可能消耗较多资源。它允许你通过 ignored 选项排除目录来优化。
// chokidar: 优化大规模监听
const watcher = chokidar.watch('.', {
ignored: (path) => path.includes('node_modules') || path.includes('.git')
});
watchpack 在这方面表现最佳。它默认不监听 node_modules 中的每个文件,而是监听目录的时间戳。只有当目录时间戳变化时,它才会深入检查。这极大地减少了文件描述符的占用。
// watchpack: 目录级监听优化
const wp = new Watchpack();
// 它智能地决定监听文件还是目录,以节省资源
wp.watch(['index.js'], ['src', 'node_modules']);
node-watch 在文件数量巨大时,由于纯 JS 实现和可能的轮询回退,CPU 占用可能高于 chokidar。它适合中小型项目或对原生模块有限制的场景。
// node-watch: 限制递归深度
watch('src', { recursive: true, maxDepth: 3 }, (evt, name) => {
// 处理逻辑
});
gaze 和 watch 在大规模文件树下表现较差,容易发生事件丢失或内存泄漏,这也是它们被现代工具弃用的主要原因。
// watch: 缺乏现代优化
const watch = require('watch');
watch.watchTree('src', function (f, curr, prev) {
// 在大量文件变更时可能阻塞事件循环
});
文件系统操作充满不确定性:编辑器如何保存文件?是原子写入还是直接覆盖?网络驱动器是否支持事件?
chokidar 处理得最完善。它能区分 add, change, unlink, unlinkDir 等细粒度事件,并能处理文件重命名(通常表现为 unlink + add)。
// chokidar: 细粒度事件
watcher
.on('add', path => console.log(`File ${path} was added`))
.on('unlink', path => console.log(`File ${path} was removed`))
.on('error', error => console.log(`Watcher error: ${error}`));
watchpack 抽象了这些细节,它更关心“构建是否需要重新运行”。它提供 aggregated 事件,将短时间内的多次变更合并为一次通知,防止构建风暴。
// watchpack: 事件聚合
wp.on('aggregated', (changes, removals) => {
// 一次性处理所有变更,适合触发构建
rebuild(changes);
});
node-watch 提供了类似 chokidar 的事件,但在某些网络文件系统(NAS)上可能需要强制开启轮询模式才能可靠工作。
// node-watch: 强制轮询模式
watch('src', { recursive: true, usePolling: true }, (evt, name) => {
// 在 NFS 或 Docker 挂载卷上更可靠
});
sane 曾经试图提供统一的接口(支持 Watchman, fsevents 等),但配置复杂且维护停滞。现在除非你在使用旧版 React Native 或 Jest,否则不应考虑。
// sane: 复杂的后端选择 (已不推荐)
const sane = require('sane');
const watcher = sane('src', { glob: ['**/*.js'] });
watcher.on('change', (filepath, root, stat) => { });
chokidar 在 macOS 上依赖 fsevents,这是一个可选的原生依赖。如果编译失败,它会自动回退到原生 fs.watch,保证安装不会报错,但性能会下降。
node-watch 没有原生依赖,安装速度最快,且在 CI/CD 环境或 Alpine Linux 等精简容器中无需安装 Python 或 C++ 构建工具。
watchpack 同样依赖 fsevents 作为可选依赖,但其核心逻辑对原生模块的依赖较少,更侧重于 JS 层的逻辑优化。
gaze, watch, filewatcher 虽然也没有复杂的原生依赖,但由于不再维护,可能存在未修复的安全漏洞或兼容性 Bug。
| 特性 | chokidar | watchpack | node-watch | gaze / watch |
|---|---|---|---|---|
| 维护状态 | ✅ 积极维护 | ✅ 积极维护 | ✅ 积极维护 | ❌ 已归档/停止 |
| 原生依赖 | 可选 (fsevents) | 可选 (fsevents) | 无 (纯 JS) | 无 |
| 递归监听 | ✅ 支持 | ✅ 支持 (智能) | ✅ 支持 | ⚠️ 有限支持 |
| 事件聚合 | ❌ (需自行实现) | ✅ 内置支持 | ❌ | ❌ |
| 适用场景 | 通用应用/DevServer | 构建工具/Bundler | 无原生环境/容器 | ❌ 不推荐 |
| API 复杂度 | 低 | 中 | 低 | 低 |
对于 90% 的前端项目,直接使用 chokidar。它是经过生产环境验证的“安全选择”,文档完善,社区支持好,能帮你避开绝大多数文件监听的坑。
如果你在开发构建工具(如自定义的 Webpack Loader 或 Bundler),请研究 watchpack。它对大量文件监听的优化策略(目录时间戳轮询)是 chokidar 不具备的,能显著提升大型项目的构建性能。
如果你在容器化环境或无构建工具链的环境中,node-watch 是一个轻量且可靠的替代品,特别是当你想避免 node-gyp 编译问题时。
对于 gaze, watch, sane, filewatcher,请将它们视为“遗留技术”。如果在新项目中看到它们,建议制定计划迁移到 chokidar,以减少未来的维护负担和潜在风险。
选择 chokidar 作为大多数项目的默认方案。它是目前生态中最成熟、维护最积极的库,被 Vite、Webpack 等主流工具采用。如果你需要跨平台一致性、递归监听和高性能,这是首选。
选择 watchpack 如果你正在开发类似 Webpack 的构建工具,且需要处理巨大的 node_modules 目录。它针对大规模文件树进行了优化,支持延迟监听和聚合事件,适合构建场景而非通用应用。
不建议在新项目中使用 sane。虽然它曾被 Jest 使用,但现已不再积极维护,且社区支持度下降。除非你维护依赖它的旧版工具链,否则应评估迁移到 chokidar。
不建议在新项目中使用 gaze。该库已归档(archived),不再维护。虽然它曾经流行于 Grunt 时代,但现代项目应迁移到 chokidar 以获得更好的支持和安全性。
选择 node-watch 如果你希望避免原生绑定(native bindings)或 C++ 依赖,纯 JavaScript 实现更易于调试和在某些受限环境中运行。它在性能和兼容性之间取得了不错的平衡。
不建议在新项目中使用 watch。这是一个非常古老的库,功能有限且不再维护。它的 API 设计较旧,缺乏现代文件监听所需的递归和去抖动特性。
不建议在新项目中使用 filewatcher。该库处于非活跃状态,功能较为基础,缺乏对复杂场景(如网络文件系统、大量文件)的优化,社区已转向更现代的替代方案。
Minimal and efficient cross-platform file watching library
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:
add / change / unlink (and addDir / unlinkDir) events, verified, deduplicated, with
paths on every platform.fs.watch by default, which keeps CPU usage down; stat-based polling is available for
network and other unusual filesystems.atomic) and chunked writes of large files (awaitWriteFinish) are
handled.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.
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 });
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,
});
ignored (default: none). One matcher or an array of matchers. The whole path is tested (as
passed to watch(), joined with cwd if set), not just the basename. Ignoring a directory
ignores everything inside it. Directories above a path passed to watch() / add() are never
ignored, so a missing path is still watched through its parent; their other contents are still
filtered. A matcher is one of:
cwd (or the process
cwd). Globs are not supported; see upgrading for the replacement pattern./(^|\/)\../ for dotfiles or /\/node_modules\//.(path, stats?) => boolean: may be called twice per path, first with the path
only, then with the path and its fs.Stats, so
guard stat-based checks with stats?.isFile().{ path, recursive?: boolean }: an exact path, plus its subtree when
recursive is true.ignoreInitial (default: false). When true, add / addDir are not emitted for paths
discovered during the initial scan (before ready).followSymlinks (default: true). When false, symlinks are watched as themselves rather
than followed; retargeting a link emits change.cwd (no default). Base directory that paths are resolved against; emitted paths are
relative to it.depth (default: undefined, unlimited). Maximum number of subdirectory levels to traverse.
Infinity means unlimited.backend (default: auto). Selects the filesystem observation backend:
auto uses native recursive watching on macOS and Windows and native per-directory
watching elsewhere.native uses one fs.watch subscription per directory.native-recursive prefers fs.watch({ recursive: true }) and falls back to per-directory
watching where recursive watching is unavailable. A finite depth also uses per-directory
watching so nothing beyond the requested tree is subscribed.polling uses Chokidar's stat-based polling scheduler. Useful for network and other
non-standard filesystems; uses more CPU.pollingInterval (default: 100) and pollingBinaryInterval (default: 300, for recognized
binary file extensions): polling periods in milliseconds, polling backend only. Polling compares
size, modification time, existence, and (except on Windows) inode between polls; an in-place
write that changes none of these is not detected.CHOKIDAR_USEPOLLING forces polling when truthy and disables it when
falsy, even if backend: 'polling' is set in code; CHOKIDAR_INTERVAL overrides
pollingInterval.usePolling: true means backend: 'polling';
interval / binaryInterval mean pollingInterval / pollingBinaryInterval (the new
spellings win when both are given).atomic (default: true with native backends, false with polling; or a number of
milliseconds). Editors that save through a temp file and rename produce unlink then add;
within the window (100 ms by default) Chokidar emits a single change instead. It also ignores
common editor temp files (.swp / .swx, ~ backups, Sublime .subl*.tmp).awaitWriteFinish (default: false). By default add / change fire as soon as a file
appears or changes, which for large or chunked writes can be before the write is finished.
Set to true (or { stabilityThreshold: 2000, pollInterval: 100 }) to hold add / change
until the file size has stayed constant for stabilityThreshold ms, checked every
pollInterval ms. The right threshold depends on the OS and hardware: higher is safer and less
responsive. Events from the initial scan are not held.alwaysStat (default: false). Always pass an
fs.Stats object with add / addDir /
change, issuing an extra stat when the backend did not provide one.ignorePermissionErrors (default: false). When true, EPERM / EACCES errors from
unreadable paths are suppressed instead of emitted.persistent (default: true). Whether the watcher keeps the process alive while it is
watching..add(paths): start watching more files or directories (string or array)..unwatch(paths): stop watching files or directories (string or array). Synchronous; the paths
stay ignored until they are .add()ed again..close(): async and terminal. Removes all listeners and stops all owned work. Repeated
calls return the same Promise; once closing has started, .add() throws and a new FSWatcher
is required..getWatched(): an object whose keys are the watched directories (absolute unless cwd is
set) and whose values are arrays of the entry names inside each..on(event, listener): FSWatcher is an EventEmitter; see events below.| 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 |
ENOSPC: System limit for number of file watchers reached (Linux): the inotify watch limit
is exhausted. Raise it with
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p, or
watch less: narrow paths, add ignored (for example node_modules), set depth.EMFILE: too many open files: the process file-descriptor limit is exhausted. Watch less as
above, raise the limit (ulimit -n 65536), or use backend: 'polling', which holds no watch
handles at the cost of CPU.fsevents-related install errors (WARN optional dep failed, fsevents is not a constructor)
are solved by upgrading to v4+.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+
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.
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.
MIT (c) Paul Miller (https://paulmillr.com), see LICENSE file.