这些包用于监测文件系统的变化,常用于开发服务器、构建工具或自动化脚本。chokidar 是目前最稳定且跨平台的库,被广泛集成于主流工具链中。nodemon 是专为开发设计的命令行工具,用于自动重启 Node.js 进程。gaze、sane 和 watch 属于早期方案,现在大多已不再推荐用于新项目,建议优先评估 chokidar。
在 Node.js 生态中,监听文件变化是构建工具、开发服务器和自动化脚本的核心需求。然而,不同操作系统对文件系统事件的实现差异巨大,导致原生 fs.watch 常常不可靠。chokidar、nodemon、node-watch 等包应运而生,旨在解决这些问题。本文将深入对比这些方案的技术细节,帮助你做出正确的架构决策。
启动监听的方式直接影响了代码的可读性和集成难度。
chokidar 提供了链式调用和事件发射器模式,配置灵活。
const chokidar = require('chokidar');
const watcher = chokidar.watch('src/**/*.js', {
ignored: /node_modules/,
persistent: true
});
nodemon 主要作为 CLI 工具使用,但也提供 JS API 用于编程式控制。
const nodemon = require('nodemon');
nodemon({
script: 'app.js',
ext: 'js json',
ignore: ['test/*']
});
node-watch 接口简单,直接返回事件发射器。
const watch = require('node-watch');
const watcher = watch('src', { recursive: true });
gaze 使用构造函数初始化,支持 glob 模式。
const Gaze = require('gaze').Gaze;
const gaze = new Gaze('src/**/*.js');
sane 需要指定具体的后端实现(如 NodeWatcher)。
const watcher = require('sane');
const w = new watcher.NodeWatcher('src');
watch 是最古老的 API 风格,基于回调。
const watch = require('watch');
watch.watchTree('src', function (f, curr, prev) {
// 处理变化
});
处理文件增加、变化和删除的方式决定了业务逻辑的复杂度。
chokidar 区分详细的事件类型,便于精确控制。
watcher
.on('add', path => console.log(`File ${path} added`))
.on('change', path => console.log(`File ${path} changed`))
.on('unlink', path => console.log(`File ${path} removed`));
nodemon 主要关注重启事件,但也允许监听自定义变化。
nodemon.on('restart', files => {
console.log('App restarted due to:', files);
});
node-watch 提供统一的事件流,需判断事件类型。
watcher.on('update', (event, filePath) => {
if (event === 'remove') {
console.log(`${filePath} removed`);
}
});
gaze 通过回调处理特定事件。
gaze.on('all', (event, filepath) => {
console.log(event, filepath);
});
sane 类似 chokidar,使用事件发射器。
w.on('all', (event, filePath) => {
console.log(event, filePath);
});
watch 将所有信息传入单个回调函数。
watch.watchTree('src', function (f, curr, prev) {
if (typeof f == 'object' && f === null) {
// 遍历结束
} else {
console.log('File changed:', f);
}
});
这是选择监听库时最重要的考量因素。Windows、macOS 和 Linux 对文件事件的报告机制完全不同。
chokidar 专为解决跨平台不一致而生。它在 Windows 上使用 fs.watchFile 轮询作为后备,在 Linux 上使用 inotify。它能正确处理文件重命名、原子写入等边缘情况。
// chokidar 自动处理原子写入导致的 unlink/add 序列
watcher.on('unlink', path => {
// 不会因编辑器临时文件误触发
});
node-watch 基于原生 fs.watch,在某些系统上可能会丢失事件或重复触发,适合简单场景。
// 可能在某些系统上对同一变化触发多次
watcher.on('update', (event, filePath) => {
// 需自行去重
});
nodemon 内部通常依赖 chokidar 或其他监听器,专注于进程管理而非底层文件事件稳定性。
// 内部封装了监听逻辑,用户无需关心底层实现
nodemon({ script: 'app.js' });
gaze、sane 和 watch 在旧版系统中表现尚可,但在现代文件系统和高并发写入场景下,容易出现漏报或性能瓶颈。
// 旧库可能无法正确处理大量文件同时变化
gaze.on('all', (event, filepath) => {
// 可能在高负载下丢失事件
});
选择库不仅是选功能,更是选维护团队。废弃的库会带来安全漏洞和兼容性风险。
chokidar 处于活跃维护状态,定期修复 Bug 并适配新 Node.js 版本。它是 Webpack、Vite、Rollup 等主流工具的底层依赖。
nodemon 同样活跃,是 Node.js 开发者的标准配置工具。
node-watch 维护频率较低,但核心功能稳定,适合轻量级需求。
gaze 已停止维护。GitHub 仓库已归档,不再接受 PR 或修复。
sane 主要用于旧版 Jest,现代版本已转向其他方案。通用场景下不再推荐。
watch 极其古老,多年未更新。存在已知问题且无修复计划。
| 特性 | chokidar | nodemon | node-watch | gaze / sane / watch |
|---|---|---|---|---|
| 主要用途 | 构建工具/底层库 | 开发服务器自动重启 | 简单脚本监听 | 遗留系统维护 |
| 跨平台支持 | ✅ 优秀 | ✅ 优秀 (封装) | ⚠️ 一般 | ❌ 较差 |
| API 现代性 | ✅ 现代 Promise/Event | ✅ 配置驱动 | ✅ 简单 | ❌ 古老回调 |
| 维护状态 | 🟢 活跃 | 🟢 活跃 | 🟡 稳定 | 🔴 停止维护 |
| 推荐指数 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ (特定场景) | ⭐⭐⭐ | ❌ 不推荐 |
chokidar 是构建可靠文件监听功能的唯一推荐选择。它 — 就像瑞士军刀一样 — 能处理各种操作系统的怪异行为,让你无需关心底层细节。如果你是在编写打包器、CLI 工具或需要精确控制文件变化的应用,请直接使用它。
nodemon 是开发 Node.js 后端时的最佳伴侣。不要试图用 chokidar 自己写一个重启脚本,除非你有特殊需求。nodemon 已经处理了进程信号、崩溃恢复和配置加载等复杂逻辑。
node-watch 可以作为轻量级替代方案,但请确保你的目标环境单一(例如仅在 Linux 服务器上运行)。
gaze、sane 和 watch 应被视为技术债务。如果你在新项目中看到它们,请计划迁移到 chokidar。它们的存在只会增加未来的维护成本,而不会带来任何现代优势。
核心原则:在基础设施层面,稳定性优于新奇性。文件监听是构建系统的基石,基石不稳,上层建筑随时可能崩塌。选择经过大规模生产环境验证的 chokidar,是对项目长期健康的负责。
选择 chokidar 如果你正在构建需要高可靠性的工具(如打包器、CLI 或自定义开发服务器)。它解决了不同操作系统下文件监听的差异,提供了统一且稳定的 API,是目前社区的事实标准。
选择 nodemon 如果你正在开发 Node.js 后端服务,并且需要在文件变化时自动重启进程。它是一个开箱即用的开发工具,而不是用于构建其他工具的底层库。
不建议在新项目中使用 sane。它曾用于 Jest 等工具,但现代工具链已转向 chokidar。除非你是在维护依赖它的旧版测试框架,否则应避免使用。
不建议在新项目中使用 gaze。该库已停止维护多年,功能已被 chokidar 完全取代。仅在维护遗留代码库时可能遇到,遇到时应计划迁移。
选择 node-watch 如果你需要简单的脚本监听且希望依赖更接近原生 fs.watch 的行为。它比 chokidar 轻量,但在处理复杂跨平台边缘情况时不如 chokidar 稳健。
不建议在新项目中使用 watch。这是一个非常古老的库,缺乏跨平台支持且已不再维护。它的功能有限,无法满足现代开发需求。
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.