chokidar、gaze、node-watch 和 watchpack 都是用于在 Node.js 环境中监听文件系统变化的工具库,它们封装了底层的 fs.watch 或 fs.watchFile,以提供更稳定、跨平台、功能丰富的文件变更通知机制。这类库广泛应用于构建工具(如 Webpack、Vite)、开发服务器热重载、自动化脚本等场景,解决原生 API 在不同操作系统下行为不一致、事件触发不稳定或缺失等问题。
在前端工程化中,监听文件变化是开发服务器热更新、构建工具增量编译等核心功能的基础。Node.js 原生的 fs.watch 虽然可用,但在不同操作系统下行为不一致(例如 macOS 对大小写不敏感、Windows 事件合并、Linux inotify 限制等),且容易漏报或误报。为此,社区涌现出多个封装库。本文将从实际工程角度,深入比较 chokidar、gaze、node-watch 和 watchpack 的技术细节与适用场景。
首先明确:gaze 已被官方废弃。在其 npm 页面 和 GitHub 仓库 中均有明确提示,建议用户迁移到 chokidar。因此,新项目绝不应选用 gaze,以下分析仅作历史参考。
所有库都提供类似 EventEmitter 的接口,通过 add/watch 添加监听路径,通过 on('change', ...) 监听事件。但细节差异显著。
chokidar:功能最全的行业标准chokidar 提供高度可配置的监听器,支持 glob 模式、忽略规则、等待文件写入完成等。
// chokidar
const chokidar = require('chokidar');
const watcher = chokidar.watch('src/**/*.js', {
ignored: /(^|[\/\\])\../, // 忽略 . 开头的文件
persistent: true,
awaitWriteFinish: {
stabilityThreshold: 2000,
pollInterval: 100
}
});
watcher.on('add', path => console.log('File added:', path));
watcher.on('change', path => console.log('File changed:', path));
watcher.on('unlink', path => console.log('File removed:', path));
gaze:已废弃的旧方案gaze 使用 glob 模式,但 API 较老,且不处理文件写入未完成的问题。
// gaze (已废弃,仅作示例)
const gaze = require('gaze');
gaze('src/**/*.js', function(err, watcher) {
this.on('all', function(event, filepath) {
console.log(event, filepath); // 'added', 'changed', 'deleted'
});
});
node-watch:轻量简洁node-watch API 极简,支持递归监听和过滤函数,但不内置 glob 支持(需自行处理)。
// node-watch
const watch = require('node-watch');
const watcher = watch('src', { recursive: true }, function(evt, name) {
console.log(evt, name); // 'update', 'remove'
});
// 或使用过滤函数
watch('src', {
recursive: true,
filter: (f) => !/\.tmp$/.test(f)
}, callback);
watchpack:Webpack 定制化方案watchpack 设计用于大规模项目,需显式调用 watch 方法并传入文件/目录列表,支持时间戳和文件哈希比对。
// watchpack
const Watchpack = require('watchpack');
const wp = new Watchpack({
aggregateTimeout: 300, // 合并事件间隔
followSymlinks: true
});
wp.watch({
files: ['package.json'],
directories: ['src']
}, () => {
// 回调在变化后触发
const changes = wp.getAggregated();
console.log('Changed files:', changes.changedFiles);
console.log('Removed files:', changes.removedFiles);
});
chokidar:通过 fsevents(macOS)、inotify(Linux)和 ReadDirectoryChangesW(Windows)等原生绑定,最大程度保证各平台行为一致。默认启用 usePolling: false,在大多数场景下高效可靠;若遇权限问题可回退到轮询模式。node-watch:主要封装 fs.watch,在 macOS 和 Windows 上表现尚可,但在 Linux 下可能因 inotify 限制(如监控大量文件)而失效,此时需手动启用轮询(usePolling: true)。watchpack:继承 Webpack 的实战经验,对大型项目(数千文件)做了优化,内部使用 chokidar 作为底层(v2+),因此兼容性与 chokidar 一致。gaze:依赖 fs.watch 和 fs.watchFile,在旧版 Node.js 中存在较多平台问题,且无后续修复。chokidar:原生支持字符串、正则、函数或数组形式的 ignored 选项,且与 glob 模式无缝集成。node-watch:仅支持 filter 函数,需自行实现 glob 匹配逻辑。watchpack:通过 ignored 选项支持正则或函数,但不直接处理 glob。gaze:支持 glob 模式中的排除语法(如 !src/*.spec.js),但灵活性有限。编辑器保存大文件时,fs.watch 可能多次触发事件。chokidar 的 awaitWriteFinish 选项可等待文件稳定后再触发,避免中间状态干扰。
// chokidar 特有
chokidar.watch('file.txt', {
awaitWriteFinish: true
}).on('change', path => {
// 仅在文件写入完成后触发
});
其他库均无此功能,需自行实现防抖或延时逻辑。
chokidar 和 watchpack 通过原生绑定和事件聚合显著优于纯 JavaScript 方案。node-watch 在启用轮询时 CPU 占用较高。watchpack 额外维护文件时间戳和哈希缓存,适合需要精确判断内容是否变化的场景(如 Webpack 的缓存失效)。chokidar:因其稳定性、功能完整性和社区支持,已成为事实标准(被 Vite、Rollup、Jest 等广泛采用)。node-watch:若项目简单、无需 glob 或高级忽略规则,其零依赖(除 Node.js 外)和简洁 API 是优势。watchpack:若需与 Webpack 的缓存机制协同工作,直接使用其内部监听层可避免重复监听和状态不一致。gaze:立即迁移到 chokidar,API 差异可通过少量代码调整解决。| 特性 | chokidar | gaze (废弃) | node-watch | watchpack |
|---|---|---|---|---|
| 维护状态 | ✅ 活跃 | ❌ 已废弃 | ✅ 活跃 | ✅ 活跃 (Webpack 生态) |
| 跨平台兼容性 | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ (基于 chokidar) |
| Glob 模式支持 | ✅ 原生 | ✅ 基础 | ❌ 需自行实现 | ❌ |
| 忽略规则 | ✅ 灵活 | ⚠️ 有限 | ⚠️ 仅函数过滤 | ✅ 正则/函数 |
| 写入完成检测 | ✅ awaitWriteFinish | ❌ | ❌ | ❌ |
| 大规模性能 | ⭐⭐⭐⭐ | ⭐ | ⭐⭐ | ⭐⭐⭐⭐⭐ |
| 典型用户 | Vite, Jest, Rollup | — | 小型工具 | Webpack |
chokidar:它解决了绝大多数文件监听痛点,且经过大规模验证。node-watch。watchpack。gaze。文件监听看似简单,实则充满平台差异和边缘情况。选择一个成熟、活跃维护的库,能让你避免陷入调试 fs.watch 的泥潭,把精力集中在核心业务上。
选择 chokidar 如果你需要一个功能全面、跨平台兼容性极佳、社区广泛采用且持续维护的文件监听方案。它特别适合构建工具、CLI 工具或任何对可靠性要求高的生产环境,支持深度目录监听、忽略规则、延迟触发等高级特性,并能自动处理 macOS、Linux 和 Windows 的差异。
不要在新项目中使用 gaze,因为该包已在 npm 上被官方标记为废弃(deprecated),其 GitHub 仓库也已归档。虽然它曾提供基于 glob 模式的监听能力,但缺乏现代维护和 bug 修复,应优先评估 chokidar 或 node-watch 等活跃替代品。
选择 node-watch 如果你追求轻量级、API 简洁且不需要复杂配置的监听需求。它直接封装 fs.watch 并修复了部分平台问题,支持递归监听和基本过滤,适合小型脚本或对依赖体积敏感的场景,但功能不如 chokidar 丰富,且在极端边缘情况下的稳定性略逊一筹。
选择 watchpack 如果你正在开发或深度定制基于 Webpack 的构建系统,或需要与 Webpack 的缓存和增量编译机制紧密集成。它是 Webpack 内部使用的文件监听层,针对大规模项目优化了性能,但作为通用库其文档和独立使用体验不如 chokidar,通常不建议在非 Webpack 生态中直接使用。
Minimal and efficient cross-platform file watching library
There are many reasons to prefer Chokidar to raw fs.watch / fs.watchFile in 2026:
renameatomic option
awaitWriteFinish option
Chokidar relies on the Node.js core fs module, but when using
fs.watch and fs.watchFile for watching, it normalizes the events it
receives, often checking for truth by getting file stats and/or dir contents.
The fs.watch-based implementation is the default, which
avoids polling and keeps CPU usage down. Be advised that chokidar will initiate
watchers recursively for everything within scope of the paths that have been
specified, so be judicious about not wasting system resources by watching much
more than needed. For some cases, fs.watchFile, which utilizes polling and uses more resources, is used.
Made for Brunch in 2012, it is now used in ~30 million repositories and has proven itself in production environments.
Install with npm:
npm install chokidar
Use it in your code:
import chokidar from 'chokidar';
// One-liner for current directory
chokidar.watch('.').on('all', (event, path) => {
console.log(event, path);
});
// Extended options
// ----------------
// Initialize watcher.
const watcher = chokidar.watch('file, dir, or array', {
ignored: (path, stats) => stats?.isFile() && !path.endsWith('.js'), // only watch js files
persistent: true,
});
// Something to use when events are received.
const log = console.log.bind(console);
// Add event listeners.
watcher
.on('add', (path) => log(`File ${path} has been added`))
.on('change', (path) => log(`File ${path} has been changed`))
.on('unlink', (path) => log(`File ${path} has been removed`));
// More possible events.
watcher
.on('addDir', (path) => log(`Directory ${path} has been added`))
.on('unlinkDir', (path) => log(`Directory ${path} has been removed`))
.on('error', (error) => log(`Watcher error: ${error}`))
.on('ready', () => log('Initial scan complete. Ready for changes'))
.on('raw', (event, path, details) => {
// internal
log('Raw event info:', event, path, details);
});
// 'add', 'addDir' and 'change' events also receive stat() results as second
// argument when available: https://nodejs.org/api/fs.html#fs_class_fs_stats
watcher.on('change', (path, stats) => {
if (stats) console.log(`File ${path} changed size to ${stats.size}`);
});
// Watch new files.
watcher.add('new-file');
watcher.add(['new-file-2', 'new-file-3']);
// Get list of actual paths being watched on the filesystem
let watchedPaths = watcher.getWatched();
// Un-watch some files.
await watcher.unwatch('new-file');
// Stop watching. The method is async!
await watcher.close().then(() => console.log('closed'));
// Full list of options. See below for descriptions.
// Do not use this example!
chokidar.watch('file', {
persistent: true,
// ignore .txt files
ignored: (file) => file.endsWith('.txt'),
// watch only .txt files
// ignored: (file, _stats) => _stats?.isFile() && !file.endsWith('.txt'),
awaitWriteFinish: true, // emit single event when chunked writes are completed
atomic: true, // emit proper events when "atomic writes" (mv _tmp file) are used
// The options also allow specifying custom intervals in ms
// awaitWriteFinish: {
// stabilityThreshold: 2000,
// pollInterval: 100
// },
// atomic: 100,
interval: 100,
binaryInterval: 300,
cwd: '.',
depth: 99,
followSymlinks: true,
ignoreInitial: false,
ignorePermissionErrors: false,
usePolling: false,
alwaysStat: false,
});
chokidar.watch(paths, [options])
paths (string or array of strings). Paths to files, dirs to be watched
recursively.options (object) Options object as defined below:persistent (default: true). Indicates whether the process
should continue to run as long as files are being watched.ignored function, regex, or path. Defines files/paths to be ignored.
The whole relative or absolute path is tested, not just filename. If a function with two arguments
is provided, it gets called twice per path - once with a single argument (the path), second
time with two arguments (the path and the
fs.Stats
object of that path).ignoreInitial (default: false). If set to false then add/addDir events are also emitted for matching paths while
instantiating the watching as chokidar discovers these file paths (before the ready event).followSymlinks (default: true). When false, only the
symlinks themselves will be watched for changes instead of following
the link references and bubbling events through the link's path.cwd (no default). The base directory from which watch paths are to be
derived. Paths emitted with events will be relative to this.usePolling (default: false).
Whether to use fs.watchFile (backed by polling), or fs.watch. If polling
leads to high CPU utilization, consider setting this to false. It is
typically necessary to set this to true to successfully watch files over
a network, and it may be necessary to successfully watch files in other
non-standard situations. Setting to true explicitly on MacOS overrides the
useFsEvents default. You may also set the CHOKIDAR_USEPOLLING env variable
to true (1) or false (0) in order to override this option.usePolling: true)
interval (default: 100). Interval of file system polling, in milliseconds. You may also
set the CHOKIDAR_INTERVAL env variable to override this option.binaryInterval (default: 300). Interval of file system
polling for binary files.
(see list of binary extensions)alwaysStat (default: false). If relying upon the
fs.Stats
object that may get passed with add, addDir, and change events, set
this to true to ensure it is provided even in cases where it wasn't
already available from the underlying watch events.depth (default: undefined). If set, limits how many levels of
subdirectories will be traversed.awaitWriteFinish (default: false).
By default, the add event will fire when a file first appears on disk, before
the entire file has been written. Furthermore, in some cases some change
events will be emitted while the file is being written. In some cases,
especially when watching for large files there will be a need to wait for the
write operation to finish before responding to a file creation or modification.
Setting awaitWriteFinish to true (or a truthy value) will poll file size,
holding its add and change events until the size does not change for a
configurable amount of time. The appropriate duration setting is heavily
dependent on the OS and hardware. For accurate detection this parameter should
be relatively high, making file watching much less responsive.
Use with caution.
options.awaitWriteFinish can be set to an object in order to adjust
timing params:awaitWriteFinish.stabilityThreshold (default: 2000). Amount of time in
milliseconds for a file size to remain constant before emitting its event.awaitWriteFinish.pollInterval (default: 100). File size polling interval, in milliseconds.ignorePermissionErrors (default: false). Indicates whether to watch files
that don't have read permissions if possible. If watching fails due to EPERM
or EACCES with this set to true, the errors will be suppressed silently.atomic (default: true if useFsEvents and usePolling are false).
Automatically filters out artifacts that occur when using editors that use
"atomic writes" instead of writing directly to the source file. If a file is
re-added within 100 ms of being deleted, Chokidar emits a change event
rather than unlink then add. If the default of 100 ms does not work well
for you, you can override it by setting atomic to a custom value, in
milliseconds.chokidar.watch() produces an instance of FSWatcher. Methods of FSWatcher:
.add(path / paths): Add files, directories for tracking.
Takes an array of strings or just one string..on(event, callback): Listen for an FS event.
Available events: add, addDir, change, unlink, unlinkDir, ready,
raw, error.
Additionally all is available which gets emitted with the underlying event
name and path for every event other than ready, raw, and error. raw is internal, use it carefully..unwatch(path / paths): Stop watching files or directories.
Takes an array of strings or just one string..close(): async Removes all listeners from watched files. Asynchronous, returns Promise. Use with await to ensure bugs don't happen..getWatched(): Returns an object representing all the paths on the file
system being watched by this FSWatcher instance. The object's keys are all the
directories (using absolute paths unless the cwd option was used), and the
values are arrays of the names of the items contained in each directory.Check out third party chokidar-cli, which allows to execute a command on each change, or get a stdio stream of change events.
Sometimes, Chokidar runs out of file handles, causing EMFILE and ENOSP errors:
bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shellError: watch /home/ ENOSPCThere are two things that can cause it.
fs module used by chokidar: let fs = require('fs'); let grfs = require('graceful-fs'); grfs.gracefulify(fs);echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p.fs.watch
usePolling: true, which will switch backend to resource-intensive fs.watchFileAll fsevents-related issues (WARN optional dep failed, fsevents is not a constructor) are solved by upgrading to v4+.
If you've used globs before and want do replicate the functionality with v4:
// v3
chok.watch('**/*.js');
chok.watch('./directory/**/*');
// v4
chok.watch('.', {
ignored: (path, stats) => stats?.isFile() && !path.endsWith('.js'), // only watch js files
});
chok.watch('./directory');
// other way
import { glob } from 'node:fs/promises';
const watcher = watch(await Array.fromAsync(glob('**/*.js')));
// unwatching
// v3
chok.unwatch('**/*.js');
// v4
chok.unwatch(await Array.fromAsync(glob('**/*.js')));
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.