chokidar vs watchpack vs sane vs gaze vs node-watch
Node.js 文件监听库技术选型指南
chokidarwatchpacksanegazenode-watch类似的npm包:

Node.js 文件监听库技术选型指南

chokidar、gaze、node-watch、sane 和 watchpack 都是用于在 Node.js 环境中监听文件系统变化的工具库。它们广泛应用于构建工具、开发服务器和自动化脚本中,用于检测文件新增、修改或删除事件。

chokidar 是目前社区最通用的选择,解决了原生 fs.watch 在不同操作系统上的不一致性问题。gaze 早期流行但已停止维护。node-watch 提供了更简单的 API 封装。sane 专注于与 Watchman 集成以提升性能。watchpack 则由 Webpack 团队维护,针对打包场景进行了优化。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
chokidar285,174,00212,272202 kB71 个月前MIT
watchpack77,295,973404122 kB312 天前MIT
sane3,548,801386-345 年前MIT
gaze1,991,4181,148-688 年前MIT
node-watch1,177,03334026.1 kB83 年前MIT

Node.js 文件监听库:架构、性能与维护状态深度对比

在构建现代前端工程体系时,文件监听(File Watching)是开发服务器、热更新(HMR)和自动化构建的核心环节。chokidar、gaze、node-watch、sane 和 watchpack 都试图解决同一个问题:如何可靠地检测文件系统变化。但它们的实现策略、维护状态和适用场景差异巨大。

🛠️ API 设计风格:事件驱动 vs 回调驱动

不同的库提供了不同的接口风格,这直接影响代码的可读性和维护成本。

chokidar 采用标准的事件发射器模式,支持链式调用和细粒度事件控制。

// chokidar: 事件驱动
const chokidar = require('chokidar');
const watcher = chokidar.watch('src/**/*', { ignored: /node_modules/ });

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

gaze 使用回调函数注册,风格较旧,不支持现代 Promise 流程。

// gaze: 回调驱动
const gaze = require('gaze');

gaze('src/**/*', function(err, watcher) {
  watcher.on('changed', function(filepath) {
    console.log(`File ${filepath} changed`);
  });
});

node-watch 提供简洁的函数式 API,支持递归选项。

// node-watch: 函数式
const watch = require('node-watch');

watch('src', { recursive: true }, function(evt, name) {
  console.log(`%s %s`, evt, name);
});

sane 基于类实例化,配置项较为复杂,专为 Watchman 设计。

// sane: 类实例
const Watcher = require('sane').Watcher;

const watcher = new Watcher('src', { glob: ['**/*.js'] });
watcher.on('change', function(filepath, root, stat) {
  console.log(`Change in ${filepath}`);
});

watchpack 针对批量监听优化,API 更接近底层资源管理。

// watchpack: 资源管理
const Watchpack = require('watchpack');
const wp = new Watchpack({ aggregateTimeout: 1000 });

wp.watch([], ['src'], 0);
wp.on('aggregated', function(changes, removals) {
  console.log(`Changes: ${changes}`);
});

⚡ 性能与批量处理:防抖与聚合

在大型项目中,一次性保存多个文件会触发大量事件。优秀的监听库需要提供防抖(debounce)或事件聚合机制。

chokidar 内置 awaitWriteFinish 选项,可等待文件写入完成后再触发事件,避免读取到空文件。

// chokidar: 等待写入完成
const watcher = chokidar.watch('src', {
  awaitWriteFinish: { stabilityThreshold: 2000, pollInterval: 100 }
});

gaze 缺乏内置的高级防抖机制,需要开发者手动实现节流逻辑。

// gaze: 需手动防抖
let timeout;
gaze('src', function(err, watcher) {
  watcher.on('changed', function(filepath) {
    clearTimeout(timeout);
    timeout = setTimeout(() => handleBuild(filepath), 300);
  });
});

node-watch 支持基础过滤,但聚合能力较弱。

// node-watch: 基础过滤
watch('src', { filter: function(name) { return /\.js$/.test(name); } }, callback);

sane 依赖 Watchman 进行内核级事件聚合,性能极高但依赖外部工具。

// sane: 依赖 Watchman
// 配置 watchman 后,sane 自动利用其聚合能力
const watcher = new Watcher('src', { watchman: true });

watchpack 核心优势在于 aggregateTimeout,专为打包工具设计,自动合并短时间内的多次变更。

// watchpack: 自动聚合
const wp = new Watchpack({ aggregateTimeout: 1000 });
// 1 秒内的多次变更只会触发一次 'aggregated' 事件

🌍 跨平台兼容性与底层实现

不同操作系统对文件系统的通知机制不同(如 macOS 的 FSEvents,Linux 的 inotify,Windows 的 ReadDirectoryChangesW)。

  • chokidar 自动检测操作系统并选择最佳后端,在 macOS 上优先使用 fsevents 二进制模块,兼容性最好。
  • gaze 主要依赖 fs.watch,在旧版 Node.js 或特定网络文件系统上容易出现事件丢失。
  • node-watch 封装了 fs.watch,处理了部分递归问题,但在 macOS 上不如 chokidar 稳定。
  • sane 强依赖 Watchman 工具,若未安装 Watchman 则回退到 fs.watch,部署环境要求高。
  • watchpack 内部复用 chokidar 作为后端之一,但增加了针对 Webpack 依赖图的逻辑层。

⚠️ 维护状态与弃用警告

这是选型中最关键的因素。使用已弃用的库会带来安全隐患。

  • chokidar: ✅ 活跃维护。社区标准,定期更新。
  • gaze: ❌ 已弃用。README 明确建议迁移至 chokidar。
  • node-watch: ⚠️ 低维护。功能稳定但更新频率低。
  • sane: ⚠️ 特定场景。主要用于 Jest 等工具,通用性下降。
  • watchpack: ✅ 活跃维护。随 Webpack 生态更新。

📊 核心特性对比表

特性chokidargazenode-watchsanewatchpack
维护状态✅ 活跃❌ 弃用⚠️ 低维护⚠️ 特定场景✅ 活跃
跨平台✅ 优秀⚠️ 一般⚠️ 一般✅ 依赖 Watchman✅ 优秀
Glob 支持✅ 内置✅ 内置❌ 需外部✅ 内置⚠️ 有限
事件聚合✅ 内置❌ 手动❌ 手动✅ 依赖 Watchman✅ 内置
适用场景通用开发工具遗留项目简单脚本大型 Monorepo打包工具

💡 架构师建议

chokidar 是绝大多数场景下的唯一推荐 ✅。它平衡了性能、兼容性和 API 易用性,是 Vite、Parcel 等现代工具的首选底层依赖。

watchpack 仅在你需要构建类似 Webpack 的依赖图解析系统时使用 🔧。它的批量处理逻辑是为模块依赖设计的,普通文件监听不需要这么复杂。

gaze 应立即从依赖中移除 🚫。它的功能已被完全取代,继续保留只会增加技术债务。

sane 和 node-watch 属于特定 niche 场景。除非你有明确的 Watchman 基础设施或极简主义需求,否则不要引入它们。

最终结论:在 2024 年的 Node.js 工程体系中,chokidar 是文件监听的事实标准。其他库要么已退役,要么服务于极其特殊的架构需求。

如何选择: chokidar vs watchpack vs sane vs gaze vs node-watch

  • chokidar:

    选择 chokidar 如果你需要跨平台稳定的文件监听方案,它是目前社区的标准选择。它处理了 macOS、Linux 和 Windows 上的底层差异,适合大多数构建工具和开发服务器场景。

  • watchpack:

    选择 watchpack 如果你正在开发类似 Webpack 的打包工具或需要高级的批量处理功能。它针对依赖图解析进行了优化,普通业务场景使用它会显得过于沉重。

  • sane:

    选择 sane 如果你的项目已经在使用 Facebook Watchman 且位于大型 monorepo 中。它能利用 Watchman 的内核级监听能力,但在普通 Node 项目中配置成本较高。

  • gaze:

    避免在新项目中使用 gaze,因为它已 officially 标记为弃用且不再维护。其功能已被 chokidar 完全覆盖,继续使用会带来安全风险和兼容性隐患。

  • node-watch:

    选择 node-watch 如果你需要轻量级的脚本且不需要复杂的 glob 匹配。它的 API 非常简洁,适合简单的自动化任务,但功能不如 chokidar 丰富。

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.