chokidar vs fs-extra vs fsevents vs gaze vs node-watch vs watchpack
Node.js 文件监听与文件系统工具选型指南
chokidarfs-extrafseventsgazenode-watchwatchpack类似的npm包:

Node.js 文件监听与文件系统工具选型指南

chokidarfseventsgazenode-watchwatchpack 主要用于监听文件系统变化,而 fs-extra 则专注于增强 Node.js 原生的文件系统操作能力。在构建开发服务器、打包工具或自动化脚本时,选择合适的监听库至关重要,它直接影响应用的启动速度、CPU 占用率以及跨平台兼容性。chokidar 是目前社区最通用的选择,它封装了 fsevents 以在 macOS 上获得高性能,同时兼容其他系统。fs-extra 虽然不是监听库,但常与监听工具配合使用,提供如 ensureDircopy 等原子化操作。理解这些工具的底层机制和适用场景,能帮助开发者避免内存泄漏和无效的重建触发。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
chokidar012,08982.1 kB395 个月前MIT
fs-extra09,61857.7 kB132 个月前MIT
fsevents0568173 kB173 年前MIT
gaze01,154-688 年前MIT
node-watch034226.1 kB83 年前MIT
watchpack039795.7 kB104 个月前MIT

Node.js 文件监听与文件系统工具深度对比

在 Node.js 生态中,处理文件变化和操作是构建工具链的核心环节。chokidarfseventsgazenode-watchwatchpack 以及 fs-extra 各自解决了不同层面的问题。有些专注于高效监听,有些专注于文件操作便利性,还有些专为打包工具设计。让我们从架构师的角度,深入分析它们的实现机制、API 设计以及适用边界。

🏗️ 核心机制:原生绑定 vs 纯 JS 实现

文件监听的性能很大程度上取决于是否使用了操作系统的原生能力。

chokidar 是一个跨平台的封装层。它在 macOS 上会自动使用 fsevents,在 Linux 上使用 inotify,在 Windows 上使用 ReadDirectoryChangesW。这种策略保证了性能与兼容性的平衡。

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

fsevents 直接调用 macOS 的 FSEvents API。它是目前 macOS 上性能最高的监听方案,但完全不具备跨平台能力。

// fsevents: 仅限 macOS
const fsevents = require('fsevents');
const stop = fsevents('./', (path, flags, id) => {
  console.log('Event:', path, flags, id);
});
// 需要手动管理停止监听
stop();

node-watch 完全基于 Node.js 原生的 fs.watchfs.stat 实现,不依赖任何 C++ 插件。这使得它在任何 Node 环境中都能运行,但性能略低于原生方案。

// node-watch: 纯 JS 实现
const watch = require('node-watch');

watch('./src', { recursive: true, filter: /.js$/ }, (evt, name) => {
  console.log('%s changed.', name);
});

watchpack 是 Webpack 内部使用的监听器。它针对大量文件进行了优化,采用聚合触发机制,避免频繁的重建。

// watchpack: 面向打包工具优化
const Watchpack = require('watchpack');
const wp = new Watchpack({
  aggregateTimeout: 1000
});

wp.watch({ files: ['index.js'], directories: ['src'] }, 0);
wp.on('aggregated', (changes, removals) => {
  console.log('Changes:', changes, 'Removals:', removals);
});

gaze 是早期的 glob 监听库,基于 fs.watch。由于历史原因,它在处理大量文件时容易出现性能瓶颈,且目前已不再维护。

// gaze: 旧式 Glob 监听 (不推荐)
const gaze = require('gaze');

gaze('**/*.js', function(err, watcher) {
  watcher.on('changed', function(filepath) {
    console.log(filepath, 'was changed');
  });
});

fs-extra 并不提供监听功能,它是对 fs 模块的增强。它常用于监听触发后的文件操作,如移动或复制。

// fs-extra: 文件操作增强 (非监听)
const fse = require('fs-extra');

async function moveFile() {
  await fse.move('/src/file.txt', '/dest/file.txt', { overwrite: true });
  await fse.ensureDir('/dest/logs');
}

⚠️ 维护状态与弃用风险

在选择依赖时,库的维护状态直接关系到项目的长期稳定性。

  • chokidar:目前维护最活跃,是社区事实上的标准。Vite、Webpack 等主流工具均在其底层或推荐配置中使用它。
  • fsevents:持续维护,但仅作为底层依赖存在。除非你明确知道自己在做什么,否则不建议直接在应用层引入。
  • gaze已弃用 (Deprecated)。其 GitHub 仓库已归档,存在未修复的内存泄漏问题。新项目中绝对不应使用。
  • node-watch:维护状态稳定,更新频率较低,适合简单场景。
  • watchpack:由 Webpack 团队维护,稳定可靠,但文档主要面向插件开发者。
  • fs-extra:非常稳定,广泛使用,是 Node.js 文件操作的事实标准扩展。

📐 API 设计与开发体验

不同的 API 设计反映了库的设计哲学:是追求简单,还是追求控制力。

事件监听模式

chokidargaze 采用 EventEmitter 模式,适合处理复杂的生命周期。

// chokidar: 丰富的生命周期事件
watcher
  .on('add', path => console.log(`File ${path} was added`))
  .on('unlink', path => console.log(`File ${path} was removed`))
  .on('error', error => console.log(`Watcher error: ${error}`));

node-watch 的 API 更加函数式,适合快速脚本。

// node-watch: 简洁的回调风格
watch('./src', (evt, name) => {
  if (evt === 'update') {
    console.log('File updated:', name);
  }
});

文件操作便利性

fs-extra 提供了 Promise 支持,这在现代 async/await 代码中非常关键。

// fs-extra: 原生支持 Promise
const fs = require('fs-extra');

async function initProject() {
  // 如果目录不存在则创建,存在则忽略
  await fs.ensureDir('./build/assets');
  
  // 读取并解析 JSON,自动处理异常
  const data = await fs.readJson('./config.json');
  return data;
}

相比之下,使用原生 fs 或其他监听库处理文件内容时,往往需要额外的包装。

🚀 性能与资源占用

在大型项目中,文件监听器的效率直接影响开发体验。

  • fsevents:在 macOS 上几乎零 CPU 占用,因为它直接由系统内核通知。
  • chokidar:在 macOS 上表现与 fsevents 相当。在 Windows 上,由于轮询机制的开销,可能会占用更多资源,但它是 Windows 上最稳定的选择。
  • watchpack:针对“文件爆发”场景优化。当一次保存触发多个文件变更时,它会聚合事件,减少构建次数。
  • gaze:在处理数千个文件时,内存占用显著高于 chokidar,且容易丢失事件。

🛠️ 实际场景选型指南

场景 1:构建一个 Vite/Webpack 插件

推荐:watchpackchokidar 如果你需要与 Webpack 深度集成,watchpack 是内部一致的选择。如果是通用插件,chokidar 兼容性更好。

// 插件中集成 chokidar
const watcher = chokidar.watch(options.paths);
watcher.on('change', (file) => {
  compilation.invalidate(file);
});

场景 2:跨平台开发服务器 (如 Live Server)

推荐:chokidar 必须保证在 Windows、macOS 和 Linux 上行为一致。

// 开发服务器监听静态文件
const server = chokidar.watch('public', { ignoreInitial: true });
server.on('all', (event, path) => {
  io.emit('reload', path);
});

场景 3:简单的自动化脚本 (如文件备份)

推荐:node-watch 无需安装原生模块,部署简单,适合一次性脚本或 Serverless 环境。

// 备份脚本
watch('./data', { recursive: true }, () => {
  exec('rsync -av ./data/ ./backup/');
});

场景 4:文件管理工具 (如清理、移动)

推荐:fs-extra 配合监听器使用,处理具体的文件 IO。

// 监听日志文件并归档
watcher.on('add', async (file) => {
  if (file.endsWith('.log')) {
    await fse.move(file, `./archive/${Date.now()}.log`);
  }
});

📊 总结对比表

特性chokidarfs-extrafseventsgazenode-watchwatchpack
主要用途通用文件监听文件操作增强macOS 原生监听旧式 Glob 监听纯 JS 文件监听打包工具监听
跨平台✅ 优秀✅ 优秀❌ 仅 macOS✅ 一般✅ 优秀✅ 优秀
原生依赖可选 (macOS)❌ 无✅ 是❌ 无❌ 无❌ 无
维护状态✅ 活跃✅ 活跃✅ 活跃❌ 已弃用✅ 稳定✅ 活跃
Promise 支持✅ 支持✅ 原生支持❌ 回调❌ 回调✅ 支持✅ 支持
推荐指数⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐ (IO)⭐⭐ (底层)⭐ (避免)⭐⭐⭐⭐⭐⭐⭐ (工具)

💡 架构师建议

在现代前端工程化体系中,chokidar + fs-extra 是最稳健的组合。chokidar 负责精准、高效地感知变化,而 fs-extra 负责安全、便捷地执行文件操作。

避免直接使用 fsevents,除非你在编写类似 chokidar 这样的底层库。对于 gaze,请将其视为技术债务,尽快在重构中移除。如果你的工作是开发构建工具本身,深入研究 watchpack 的聚合机制会给你带来灵感。

记住,文件监听是资源密集型操作 —— 总是配置好 ignored 选项,排除 node_modules.git 目录,这能节省 90% 以上的不必要开销。

如何选择: chokidar vs fs-extra vs fsevents vs gaze vs node-watch vs watchpack

  • chokidar:

    如果你需要构建一个跨平台的文件监听服务,chokidar 是首选。它自动处理不同操作系统的差异,并在 macOS 上利用 fsevents 提升性能。适用于大多数开发服务器、热重载(HMR)插件或自动化构建脚本。

  • fs-extra:

    当你需要比 Node.js 原生 fs 模块更便捷的文件操作方法时使用,例如递归创建目录或移动文件。注意它本身不提供文件监听功能,通常与 chokidar 配合使用来处理监听后的文件操作。

  • fsevents:

    仅在你的应用仅运行于 macOS 环境且对文件监听性能有极致要求时使用。它是原生 C++ 绑定,安装复杂且不支持 Windows 或 Linux,通常作为 chokidar 的底层依赖而非直接调用。

  • gaze:

    仅用于维护旧项目。该库已不再积极维护,且存在已知的性能问题和内存泄漏风险。在新项目中应避免使用,建议迁移至 chokidar 以获得更好的稳定性和支持。

  • node-watch:

    如果你希望避免原生依赖(native dependencies)带来的安装问题,可以选择它。它完全基于 JavaScript 实现,支持递归监听,适合对安装体积敏感或环境受限的场景。

  • watchpack:

    如果你正在开发类似 Webpack 的打包工具或需要处理大量文件的高性能监听场景。它针对构建工具进行了优化,支持批量处理和延迟触发,但不适合作为通用的应用层监听库。

chokidar的README

Chokidar Weekly downloads

Minimal and efficient cross-platform file watching library

Why?

There are many reasons to prefer Chokidar to raw fs.watch / fs.watchFile in 2026:

  • Events are properly reported
    • macOS events report filenames
    • events are not reported twice
    • changes are reported as add / change / unlink instead of useless rename
  • Atomic writes are supported, using atomic option
    • Some file editors use them
  • Chunked writes are supported, using awaitWriteFinish option
    • Large files are commonly written in chunks
  • File / dir filtering is supported
  • Symbolic links are supported
  • Recursive watching is always supported, instead of partial when using raw events
    • Includes a way to limit recursion depth

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.

  • Nov 2025 update: v5 is out. Makes package ESM-only and increases minimum node.js requirement to v20.
  • Sep 2024 update: v4 is out! It decreases dependency count from 13 to 1, removes support for globs, adds support for ESM / Common.js modules, and bumps minimum node.js version from v8 to v14. Check out upgrading.

Getting started

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:

Persistence

  • persistent (default: true). Indicates whether the process should continue to run as long as files are being watched.

Path filtering

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

Performance

  • 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.
  • Polling-specific settings (effective when 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.

Errors

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

Methods & Events

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.

CLI

Check out third party chokidar-cli, which allows to execute a command on each change, or get a stdio stream of change events.

Troubleshooting

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 shell
  • Error: watch /home/ ENOSPC

There are two things that can cause it.

  1. Exhausted file handles for generic fs operations
    • Can be solved by using graceful-fs, which can monkey-patch native fs module used by chokidar: let fs = require('fs'); let grfs = require('graceful-fs'); grfs.gracefulify(fs);
    • Can also be solved by tuning OS: echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p.
  2. Exhausted file handles for fs.watch
    • Can't seem to be solved by graceful-fs or OS tuning
    • It's possible to start using usePolling: true, which will switch backend to resource-intensive fs.watchFile

All fsevents-related issues (WARN optional dep failed, fsevents is not a constructor) are solved by upgrading to v4+.

Changelog

  • v4 (Sep 2024): remove glob support and bundled fsevents. Decrease dependency count from 13 to 1. Rewrite in typescript. Bumps minimum node.js requirement to v14+
  • v3 (Apr 2019): massive CPU & RAM consumption improvements; reduces deps / package size by a factor of 17x and bumps Node.js requirement to v8.16+.
  • v2 (Dec 2017): globs are now posix-style-only. Tons of bugfixes.
  • v1 (Apr 2015): glob support, symlink support, tons of bugfixes. Node 0.8+ is supported
  • v0.1 (Apr 2012): Initial release, extracted from Brunch

Upgrading

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

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.