chokidar、gaze、node-watch、nodemon 和 watch 都是 Node.js 生态中用于监听文件系统变化的工具,但它们的定位和适用场景差异巨大。chokidar 是目前社区事实上的标准跨平台监听库,提供了稳定且一致的事件接口。gaze 和 watch 是早期的监听方案,目前大多已停止维护或不再推荐用于新项目。node-watch 是对原生 fs.watch 的轻量级封装,适合简单场景。nodemon 则是一个专门用于开发环境中自动重启 Node.js 应用的工具,虽然底层涉及文件监听,但其核心目的是进程管理而非通用文件监控。
在 Node.js 开发中,监听文件变化是构建工具、热重载(HMR)和自动化任务的核心需求。虽然表面上看这些包都在做同一件事,但它们的底层实现、稳定性和适用场景截然不同。作为架构师,我们需要清楚区分“通用监听库”与“开发工具”,并识别哪些是历史遗留产物。
首先必须明确,nodemon 与其他四个包不在同一个类别。
chokidar、gaze、node-watch、watch 是通用文件监听库。
nodemon 是开发辅助工具。
// nodemon: 专注于重启进程,而非暴露文件事件
const nodemon = require('nodemon');
nodemon({
script: 'app.js',
watch: ['src/'],
ext: 'js,json'
});
nodemon.on('restart', () => {
console.log('应用已重启');
});
// 注意:它没有提供类似 'fileChanged' 的通用事件供你处理业务逻辑
// chokidar: 专注于暴露文件事件,供你编写业务逻辑
const chokidar = require('chokidar');
const watcher = chokidar.watch('src/', {
ignored: /node_modules/,
persistent: true
});
watcher.on('change', path => {
console.log(`文件 ${path} 已修改,触发构建`);
// 这里可以执行任意逻辑,如打包、部署等
});
不同的库在事件命名和参数传递上有显著差异,这直接影响代码的可读性和迁移成本。
chokidar 使用语义清晰的事件名(add, addDir, change, unlink, unlinkDir)。
// chokidar: 语义化的事件区分
watcher.on('add', path => console.log(`新建文件:${path}`));
watcher.on('unlink', path => console.log(`删除文件:${path}`));
watcher.on('change', path => console.log(`文件变动:${path}`));
node-watch 的事件类型较为简单(update, remove)。
// node-watch: 通过事件对象传递信息
watch('src/', { recursive: true }, function(evt, name) {
console.log('%s %s', evt, name);
// evt 可能是 'update' 或 'remove'
});
gaze 使用 changed, added, deleted 事件。
chokidar。// gaze: 旧式回调风格
const gaze = require('gaze');
gaze(['**/*.js'], function(err, watcher) {
watcher.on('changed', function(filepath) {
console.log('文件被修改', filepath);
});
watcher.on('added', function(filepath) {
console.log('文件被添加', filepath);
});
});
watch (mikeal/watch) 的 API 非常原始。
watch.watchTree 方法。// watch: 原始的文件树监听
const watch = require('watch');
watch.watchTree('src/', function(f, curr, prev) {
if (typeof f == "object" && prev === null && curr === null) {
// 遍历完成
} else if (prev === null) {
console.log('新文件', f);
} else {
console.log('文件修改', f);
}
});
文件监听的性能直接影响开发体验,特别是在大型单体仓库(Monorepo)中。
chokidar 优先使用系统原生的 fs.watch,并在检测到不可靠时自动降级到 fs.watchFile(轮询)。
awaitWatcher 等机制确保事件处理完成。// chokidar: 自动处理底层差异,支持持久化监听
const watcher = chokidar.watch('project/', {
persistent: true,
usePolling: false, // 默认优先使用原生事件
interval: 100 // 仅在轮询模式下生效
});
node-watch 同样是对原生的封装,但策略更简单。
fs.watch 的某些 bug,但功能集较小。// node-watch: 简单的递归选项
watch('project/', { recursive: true }, function(evt, name) {
// 在高负载下可能不如 chokidar 稳定
});
gaze 和 watch 在旧版本 Node.js 上表现尚可,但在新版 V8 和文件系统变更下已显疲态。
// gaze: 缺乏现代优化,可能导致高 CPU 占用
gaze('**/*', function() {
// 在大型项目中,回调触发频率难以控制
});
在架构选型中,库的维护状态是决定性因素。
chokidar 处于活跃维护状态。
nodemon 处于活跃维护状态。
gaze 和 watch 基本处于停滞状态。
node-watch 维护频率较低但相对稳定。
// 风险示例:使用已停止维护的库可能导致未来升级失败
// 不推荐
const watch = require('watch');
// 推荐
const chokidar = require('chokidar');
| 特性 | chokidar | node-watch | nodemon | gaze | watch |
|---|---|---|---|---|---|
| 定位 | 通用监听库 | 通用监听库 | 开发重启工具 | 通用监听库 (旧) | 通用监听库 (旧) |
| 维护状态 | ✅ 活跃 | ⚠️ 低频 | ✅ 活跃 | ❌ 停滞 | ❌ 停滞 |
| 跨平台稳定性 | 高 | 中 | 高 (仅限重启) | 低 | 低 |
| API 现代性 | 高 (Promise 友好) | 中 | 中 | 低 (回调) | 低 (回调) |
| 适用场景 | 构建工具、生产监控 | 简单脚本 | 本地开发调试 | 遗留项目维护 | 遗留项目维护 |
| 是否推荐 | 强烈推荐 | 可选 | 开发环境推荐 | 不推荐 | 不推荐 |
在设计前端工程化体系时,文件监听模块应当是透明且可靠的。
默认选择 chokidar:无论是编写自定义 CLI、构建插件还是后端同步服务,chokidar 都是最安全的选择。它的 API 设计允许你轻松处理防抖(debounce)和批量处理,这对于避免构建风暴至关重要。
隔离 nodemon:将 nodemon 限制在 package.json 的 devDependencies 和开发脚本中。不要让它渗透到你的核心业务逻辑或部署脚本里。
清理技术债务:如果代码库中还存在 gaze 或 watch,请制定迁移计划。它们的 API 差异不大,替换为 chokidar 通常只需修改导入语句和事件名称,但能显著提升长期稳定性。
关注原子写入:在 Linux 和 macOS 上,编辑器保存文件通常是“写入临时文件 -> 重命名”的过程。chokidar 能较好地处理这种 unlink + add 的组合事件,而老旧库可能会将其误判为文件删除,导致监听失效。
选择正确的工具不仅仅是为了代码能跑,更是为了在系统规模扩大时,减少不可预知的运维成本。
如果你的项目需要跨平台稳定运行,且对文件变动的准确性要求较高,chokidar 是首选。它解决了原生 fs.watch 在不同操作系统上的不一致问题,支持忽略模式、批量事件处理等高级功能。大多数现代构建工具(如 Vite、Webpack)底层都依赖它。
如果你的目标是在开发过程中自动重启 Node.js 服务器,直接使用 nodemon。不要试图用它来做通用的文件监听任务,它的配置和事件系统都是为进程重启设计的,不适合构建流水线或数据同步场景。
仅当你维护非常老旧的项目且无法迁移时使用 gaze。该库已不再积极维护,功能已被 chokidar 等更现代的方案超越。在新架构中引入它会增加技术债务,建议尽快替换。
如果你需要比原生 fs.watch 更好用但比 chokidar 更轻量的方案,可以选择 node-watch。它适合简单的脚本工具或对依赖体积敏感的场景,但在处理复杂目录结构时不如 chokidar 健壮。
避免在新项目中使用 watch 包。它是非常早期的实现,缺乏对现代 Node.js 特性的支持,且长期未更新。其功能完全可以通过 chokidar 或原生 API 更好地实现。
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.