这五个包分为两类核心用途:文件监听器(chokidar, node-watch, watch, gulp-watch)和 Gulp 流转换插件(gulp-rename)。chokidar 是目前跨平台文件监听的事实标准;node-watch 提供轻量级的递归监听支持;watch 是早期方案,现已不再推荐;gulp-watch 和 gulp-rename 专用于 Gulp 构建流,前者用于监听文件变化触发流,后者用于在流中重命名文件。理解它们的定位差异对于构建稳定的自动化任务至关重要。
在构建自动化任务、开发服务器或同步工具时,选择合适的文件监听和处理库直接影响项目的稳定性和维护成本。这五个包虽然常出现在同一类教程中,但它们的定位截然不同。chokidar, node-watch, watch 是独立的监听库;gulp-watch 和 gulp-rename 是 Gulp 生态的插件。我们将深入对比它们的技术实现、API 设计及适用场景。
对于不依赖构建工具的独立 Node.js 脚本,选择合适的监听库是第一步。
chokidar 使用轮询和原生事件相结合的方式,解决了不同操作系统(尤其是 macOS 和 Windows)的文件事件不一致问题。
// chokidar: 跨平台稳定监听
const chokidar = require('chokidar');
const watcher = chokidar.watch('src/**/*.js', {
ignored: /node_modules/,
persistent: true
});
watcher.on('change', path => {
console.log(`File ${path} has been changed`);
});
node-watch 专注于提供递归监听支持,API 比原生 fs.watch 更友好,但功能集不如 chokidar 丰富。
// node-watch: 轻量递归监听
const watch = require('node-watch');
watch('src', { recursive: true }, (evt, name) => {
console.log('%s %s', evt, name);
});
watch 是早期的监听方案,基于轮询实现,性能开销大且不再维护。
// watch: 早期方案(已不推荐)
const watch = require('watch');
watch.watchCreateRoot('src', { persistent: true }, (f, curr, prev) => {
console.log('File changed:', f);
});
在 Gulp 构建系统中,文件操作通常以流(Stream)的形式进行。这里需要区分“监听触发”和“流处理”。
gulp-watch 允许在 Gulp 管道中直接监听文件变化,适合旧版 Gulp 工作流。
// gulp-watch: 流式监听
const gulp = require('gulp');
const watch = require('gulp-watch');
gulp.task('watch', () => {
return gulp.src('src/**/*.css')
.pipe(watch('src/**/*.css'))
.pipe(gulp.dest('dist'));
});
gulp-rename 不监听文件,它在文件通过管道时修改文件名。
// gulp-rename: 流中重命名
const gulp = require('gulp');
const rename = require('gulp-rename');
gulp.src('src/main.js')
.pipe(rename({ suffix: '.min', extname: '.js' }))
.pipe(gulp.dest('dist'));
在选择库时,维护状态是架构决策的关键因素。
| 包名 | 维护状态 | 风险提示 |
|---|---|---|
chokidar | ✅ 活跃维护 | 无,行业标准 |
gulp-rename | ✅ 活跃维护 | 仅限 Gulp 流使用 |
gulp-watch | ⚠️ 维护放缓 | Gulp 4 内置 gulp.watch 更推荐 |
node-watch | ✅ 稳定维护 | 功能相对单一 |
watch | ❌ 已弃用 | 存在跨平台 Bug,性能差 |
watch 包在 npm 上已多年未更新,社区普遍标记为过时。在 Windows 上容易出现文件锁死或事件丢失。gulp-watch 虽然可用,但 Gulp 4 引入的 gulp.watch() 方法性能更好且无需额外依赖,新项目应优先考虑内置方法。
不同的库对文件事件的处理粒度不同。
chokidar 提供细粒度的事件类型(add, change, unlink, unlinkDir)。
// chokidar: 细粒度事件
watcher.on('add', path => console.log(`Added ${path}`));
watcher.on('unlink', path => console.log(`Removed ${path}`));
node-watch 主要区分 update 和 remove 事件。
// node-watch: 基础事件
watch('src', (evt, name) => {
if (evt === 'update') console.log('Updated');
if (evt === 'remove') console.log('Removed');
});
watch 提供当前和前一个文件状态对象,但处理起来较繁琐。
// watch: 状态对比
watch.monitor('src', (f, curr, prev) => {
if (curr.nlink === 0) console.log('Removed');
});
gulp-watch 将文件事件转换为 Gulp 流对象。
// gulp-watch: 流对象
.pipe(watch('src/**/*'))
.on('change', file => console.log(file.path));
gulp-rename 不涉及事件,仅修改路径属性。
// gulp-rename: 路径修改
.pipe(rename(path => {
path.dirname += '/subdir';
path.basename += '-bak';
}));
文件监听在不同操作系统上的表现差异巨大。
chokidar: 在 Windows, macOS, Linux 上表现一致,自动处理文件系统差异。node-watch: 依赖原生绑定,在部分 Linux 发行版上可能需要配置 inotify 限制。watch: 在 Windows 上经常失效, macOS 上消耗大量 CPU。gulp-watch / gulp-rename: 依赖底层监听器(通常是 chokidar 或原生),兼容性取决于 Gulp 版本和配置。| 特性 | chokidar | node-watch | watch | gulp-watch | gulp-rename |
|---|---|---|---|---|---|
| 主要用途 | 通用文件监听 | 轻量递归监听 | 早期监听 | Gulp 流监听 | Gulp 流重命名 |
| 跨平台支持 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| 维护状态 | 活跃 | 稳定 | 弃用 | 放缓 | 活跃 |
| API 复杂度 | 中 | 低 | 低 | 中 | 低 |
| Gulp 集成 | 需手动配合 | 需手动配合 | 需手动配合 | 原生支持 | 原生支持 |
| 推荐指数 | ✅ 强烈推荐 | ✅ 推荐 | ❌ 避免 | ⚠️ 酌情使用 | ✅ 推荐 |
chokidar 是通用文件监听的首选方案 🏆。无论是编写 CLI 工具、开发服务器还是自定义构建脚本,它都能提供最佳的稳定性和兼容性。大多数现代工具链都在底层使用它。
gulp-rename 是 Gulp 工作流中的必备工具 🔧。当你需要在构建管道中修改输出文件的名称或结构时,它是标准解决方案。
gulp-watch 和 watch 属于遗留技术 🕰️。除非你在维护旧项目,否则不应在新架构中引入它们。Gulp 4 用户应使用内置 gulp.watch,独立脚本应使用 chokidar。
node-watch 适合特定场景 🎯。如果你需要极简的递归监听且不想引入 chokidar 较大的依赖树,它是一个合格的替代品。
最终结论:在新项目中,监听文件请用 chokidar,Gulp 重命名请用 gulp-rename,其余三个包仅在维护旧代码时考虑。
选择 chokidar 如果你需要最稳定的跨平台文件监听方案。它是大多数现代工具(如 Vite, Jest, Nodemon)的底层依赖,支持模糊匹配、忽略规则和多种事件类型,适合生产环境。
选择 node-watch 如果你需要比原生 fs.watch 更简单的递归监听 API,且希望依赖更少。它适合轻量级脚本或不需要复杂配置的单平台场景。
选择 gulp-rename 如果你正在使用 Gulp 构建流且需要在管道中修改文件名或扩展名。它不监听文件,只处理流中的数据,是 Gulp 生态中重命名操作的标准插件。
避免在新项目中使用 watch。该包已多年未维护,存在已知的跨平台问题和性能缺陷。官方社区普遍建议迁移到 chokidar 以获得更好的稳定性。
选择 gulp-watch 如果你维护旧的 Gulp 3 项目或需要特定的流式监听行为。但在 Gulp 4 及以上版本,建议优先使用内置的 gulp.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.