chokidar vs nodemon vs gaze vs node-watch vs watch
Node.js 文件监听方案选型与架构对比
chokidarnodemongazenode-watchwatch类似的npm包:

Node.js 文件监听方案选型与架构对比

chokidar、gaze、node-watch、nodemon 和 watch 都是 Node.js 生态中用于监听文件系统变化的工具,但它们的定位和适用场景差异巨大。chokidar 是目前社区事实上的标准跨平台监听库,提供了稳定且一致的事件接口。gaze 和 watch 是早期的监听方案,目前大多已停止维护或不再推荐用于新项目。node-watch 是对原生 fs.watch 的轻量级封装,适合简单场景。nodemon 则是一个专门用于开发环境中自动重启 Node.js 应用的工具,虽然底层涉及文件监听,但其核心目的是进程管理而非通用文件监控。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
chokidar291,272,72812,271202 kB71 个月前MIT
nodemon17,101,11526,667219 kB159 个月前MIT
gaze2,037,7531,148-688 年前MIT
node-watch1,207,01134026.1 kB83 年前MIT
watch794,2151,285-5910 年前Apache-2.0

Node.js 文件监听方案选型与架构对比

在 Node.js 开发中,监听文件变化是构建工具、热重载(HMR)和自动化任务的核心需求。虽然表面上看这些包都在做同一件事,但它们的底层实现、稳定性和适用场景截然不同。作为架构师,我们需要清楚区分“通用监听库”与“开发工具”,并识别哪些是历史遗留产物。

🏗️ 核心定位:通用库 vs 开发工具

首先必须明确,nodemon 与其他四个包不在同一个类别。

chokidar、gaze、node-watch、watch 是通用文件监听库。

  • 它们暴露文件事件(add, change, unlink)。
  • 你可以用它们触发构建、同步文件或更新缓存。
  • 它们是底层基础设施。

nodemon 是开发辅助工具。

  • 它的核心目的是监测代码变化并重启 Node 进程。
  • 虽然它底层也监听文件,但它不希望你直接处理文件事件。
  • 它是开箱即用的解决方案,而非构建模块。
// 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} 已修改,触发构建`);
  // 这里可以执行任意逻辑,如打包、部署等
});

🛠️ API 设计与事件处理

不同的库在事件命名和参数传递上有显著差异,这直接影响代码的可读性和迁移成本。

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 事件。

  • 它支持通配符匹配,但 API 风格较旧(基于回调而非 Promise 友好)。
  • 事件参数有时包含文件统计信息,但一致性不如 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);
  }
});

🐢 性能与稳定性:原生封装 vs 轮询

文件监听的性能直接影响开发体验,特别是在大型单体仓库(Monorepo)中。

chokidar 优先使用系统原生的 fs.watch,并在检测到不可靠时自动降级到 fs.watchFile(轮询)。

  • 它内部处理了 macOS 上的已知问题(如事件重复触发)。
  • 支持 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 和文件系统变更下已显疲态。

  • 它们缺乏对现代文件系统事件(如原子写入)的优化处理。
  • 容易出现“事件风暴”,导致 CPU 占用过高。
// gaze: 缺乏现代优化,可能导致高 CPU 占用
gaze('**/*', function() {
  // 在大型项目中,回调触发频率难以控制
});

⚠️ 维护状态与风险提示

在架构选型中,库的维护状态是决定性因素。

chokidar 处于活跃维护状态。

  • 它是 Vite、Rollup、Webpack 等主流工具的依赖。
  • 社区支持强大,Bug 修复及时。
  • 推荐用于所有生产级项目。

nodemon 处于活跃维护状态。

  • 但请仅将其用于本地开发环境。
  • 不推荐将其逻辑集成到生产代码中。

gaze 和 watch 基本处于停滞状态。

  • GitHub 仓库更新频率极低。
  • 存在未修复的 Issue,且不支持 Node.js 最新特性。
  • 明确建议:不要在新项目中使用。

node-watch 维护频率较低但相对稳定。

  • 适合轻量级脚本,但不适合复杂构建系统。
  • 如果未来需要扩展功能,迁移成本较高。
// 风险示例:使用已停止维护的库可能导致未来升级失败
// 不推荐
const watch = require('watch'); 

// 推荐
const chokidar = require('chokidar');

📊 总结对比表

特性chokidarnode-watchnodemongazewatch
定位通用监听库通用监听库开发重启工具通用监听库 (旧)通用监听库 (旧)
维护状态✅ 活跃⚠️ 低频✅ 活跃❌ 停滞❌ 停滞
跨平台稳定性高中高 (仅限重启)低低
API 现代性高 (Promise 友好)中中低 (回调)低 (回调)
适用场景构建工具、生产监控简单脚本本地开发调试遗留项目维护遗留项目维护
是否推荐强烈推荐可选开发环境推荐不推荐不推荐

💡 架构师建议

在设计前端工程化体系时,文件监听模块应当是透明且可靠的。

  1. 默认选择 chokidar:无论是编写自定义 CLI、构建插件还是后端同步服务,chokidar 都是最安全的选择。它的 API 设计允许你轻松处理防抖(debounce)和批量处理,这对于避免构建风暴至关重要。

  2. 隔离 nodemon:将 nodemon 限制在 package.json 的 devDependencies 和开发脚本中。不要让它渗透到你的核心业务逻辑或部署脚本里。

  3. 清理技术债务:如果代码库中还存在 gaze 或 watch,请制定迁移计划。它们的 API 差异不大,替换为 chokidar 通常只需修改导入语句和事件名称,但能显著提升长期稳定性。

  4. 关注原子写入:在 Linux 和 macOS 上,编辑器保存文件通常是“写入临时文件 -> 重命名”的过程。chokidar 能较好地处理这种 unlink + add 的组合事件,而老旧库可能会将其误判为文件删除,导致监听失效。

选择正确的工具不仅仅是为了代码能跑,更是为了在系统规模扩大时,减少不可预知的运维成本。

如何选择: chokidar vs nodemon vs gaze vs node-watch vs watch

  • chokidar:

    如果你的项目需要跨平台稳定运行,且对文件变动的准确性要求较高,chokidar 是首选。它解决了原生 fs.watch 在不同操作系统上的不一致问题,支持忽略模式、批量事件处理等高级功能。大多数现代构建工具(如 Vite、Webpack)底层都依赖它。

  • nodemon:

    如果你的目标是在开发过程中自动重启 Node.js 服务器,直接使用 nodemon。不要试图用它来做通用的文件监听任务,它的配置和事件系统都是为进程重启设计的,不适合构建流水线或数据同步场景。

  • gaze:

    仅当你维护非常老旧的项目且无法迁移时使用 gaze。该库已不再积极维护,功能已被 chokidar 等更现代的方案超越。在新架构中引入它会增加技术债务,建议尽快替换。

  • node-watch:

    如果你需要比原生 fs.watch 更好用但比 chokidar 更轻量的方案,可以选择 node-watch。它适合简单的脚本工具或对依赖体积敏感的场景,但在处理复杂目录结构时不如 chokidar 健壮。

  • watch:

    避免在新项目中使用 watch 包。它是非常早期的实现,缺乏对现代 Node.js 特性的支持,且长期未更新。其功能完全可以通过 chokidar 或原生 API 更好地实现。

chokidar的README

Chokidar Weekly downloads

Minimal and efficient cross-platform file watching library

Why?

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:

  • Proper add / change / unlink (and addDir / unlinkDir) events, verified, deduplicated, with paths on every platform.
  • Native fs.watch by default, which keeps CPU usage down; stat-based polling is available for network and other unusual filesystems.
  • Recursive watching everywhere, with an optional depth limit, path filtering, and symlink support.
  • Editor "atomic writes" (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.

Getting started

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 });

API

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,
});

Filtering

  • 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:
    • a string: an exact path. Relative strings are resolved against cwd (or the process cwd). Globs are not supported; see upgrading for the replacement pattern.
    • a RegExp: tested against the whole path with forward slashes, on Windows too, e.g. /(^|\/)\../ for dotfiles or /\/node_modules\//.
    • a function (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().
    • an object { 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

  • 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.
  • Environment overrides: CHOKIDAR_USEPOLLING forces polling when truthy and disables it when falsy, even if backend: 'polling' is set in code; CHOKIDAR_INTERVAL overrides pollingInterval.
  • Deprecated aliases kept for compatibility: usePolling: true means backend: 'polling'; interval / binaryInterval mean pollingInterval / pollingBinaryInterval (the new spellings win when both are given).

Event timing

  • 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.

Errors and lifecycle

  • 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.

Methods

  • .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.

Events

EventListener 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
readynone; the initial scan is complete
error(error)
raw(event, path, details) from the backend; unstable, use with care

Troubleshooting

  • 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+.

Changelog

  • v6 (Oct 2026): complete rewrite; new fs.watch(recursive) backend on macos + windows; requires Node.js 22+
  • v5 (Nov 2025): ESM-only; requires Node.js 20+
  • v4 (Sep 2024): remove glob support & fsevents dependency, decrease dep count from 13 to 1; requires Node.js 14+
  • v3 (Apr 2019): massive CPU & RAM consumption improvements; 17x decrease in pkg size + deps; requires Node.js 8.16+
  • v2 (Dec 2017): posix-style globs; bugfixes
  • v1 (Apr 2015): glob support, symlink support, tons of bugfixes; requires Node.js 0.8+
  • v0.1 (Apr 2012): extracted from Brunch

Upgrading

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+

Contributing

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.

Also

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.

License

MIT (c) Paul Miller (https://paulmillr.com), see LICENSE file.