chokidar vs fsevents vs gaze vs node-watch vs watch
文件监视库
chokidarfseventsgazenode-watchwatch类似的npm包:

文件监视库

文件监视库是用于监视文件系统中的变化(如文件的创建、修改、删除)并触发相应事件的工具。这些库在构建自动化工具、开发实时应用程序或实现热重载功能时非常有用。它们通过监听文件或目录的变化,帮助开发者及时响应文件系统的变化,从而实现更高效的工作流程。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

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

功能对比: chokidar vs fsevents vs gaze vs node-watch vs watch

性能

  • chokidar:

    chokidar 是一个高性能的文件监视库,特别是在处理大量文件和目录时表现出色。它使用原生的 fs.watch 和 fs.watchFile 方法,并在可能的情况下利用平台特定的优化,如 macOS 上的 fsevents,以提高监视效率。

  • fsevents:

    fsevents 是专为 macOS 设计的文件系统事件库,利用 macOS 的原生文件系统事件 API 提供极高的性能和低延迟。它在监视文件和目录变化时资源消耗非常低,适合对性能要求极高的应用。

  • gaze:

    gaze 性能相对较低,特别是在监视大量文件时。它使用 fs.watch 和 fs.watchFile 方法,但缺乏对平台特定优化的支持,可能导致在处理大量文件变化时效率不高。

  • node-watch:

    node-watch 是一个轻量级的文件监视库,性能表现良好,特别是在监视少量文件和目录时。它的资源消耗较低,适合对性能和内存使用敏感的应用,但在处理大量文件时可能不如 chokidar。

  • watch:

    watch 库的性能表现一般,适合中小规模的文件和目录监视任务。它支持递归监视,但在处理大量文件变化时可能会导致资源消耗增加,影响应用的响应速度。

跨平台支持

  • chokidar:

    chokidar 提供跨平台的文件监视支持,兼容 Windows、macOS 和 Linux。它自动根据平台选择最合适的监视方法,确保在不同操作系统上都能稳定运行。

  • fsevents:

    fsevents 仅限于 macOS 平台,利用 macOS 的原生文件系统事件 API 提供高效的监视功能。对于跨平台应用,需结合其他监视库使用。

  • gaze:

    gaze 支持跨平台文件监视,兼容 Windows、macOS 和 Linux。它使用标准的 Node.js 文件系统监视方法,确保在不同操作系统上都能正常工作。

  • node-watch:

    node-watch 提供跨平台支持,能够在 Windows、macOS 和 Linux 上监视文件和目录变化。它使用平台无关的监视方法,确保在各种操作系统环境中都能稳定运行。

  • watch:

    watch 库支持跨平台文件和目录监视,兼容 Windows、macOS 和 Linux。它使用递归监视技术,确保在不同操作系统上都能有效监视文件变化。

递归监视

  • chokidar:

    chokidar 支持递归监视目录,允许开发者监视整个目录树中的文件变化。它在递归监视时性能表现优异,特别是在处理大量子目录和文件时。

  • fsevents:

    fsevents 本身支持递归监视目录,但仅限于 macOS 平台。它利用 macOS 的原生递归监视功能,提供高效的目录树监视。

  • gaze:

    gaze 支持递归监视目录,允许使用通配符监视子目录和文件。递归监视功能实现较为简单,适合小型项目使用。

  • node-watch:

    node-watch 支持递归监视目录,允许监视整个目录树中的文件变化。它的递归监视功能实现轻量,适合资源有限的应用。

  • watch:

    watch 库支持递归监视目录,允许监视整个目录树中的文件和子目录变化。递归监视功能稳定,适合需要监视复杂目录结构的应用。

资源消耗

  • chokidar:

    chokidar 在监视大量文件时可能会消耗较多资源,但它通过优化和使用原生事件减少了资源使用。开发者可以通过配置选项(如忽略某些文件或目录)来进一步降低资源消耗。

  • fsevents:

    fsevents 资源消耗非常低,特别是在 macOS 平台上。它利用原生文件系统事件,避免了轮询,极大地减少了 CPU 和内存使用。

  • gaze:

    gaze 在监视大量文件时资源消耗较高,特别是当使用轮询(polling)方法时。它缺乏对资源优化的支持,可能导致在长时间运行的应用中出现性能瓶颈。

  • node-watch:

    node-watch 资源消耗较低,适合监视少量文件和目录。它的轻量级设计使其在使用过程中对系统资源的影响较小,但在监视大量文件时可能会出现性能下降。

  • watch:

    watch 库在监视大量文件和目录时可能会消耗较多资源,特别是在递归监视复杂目录结构时。开发者需要注意资源管理,避免因监视任务过重导致应用性能下降。

代码示例

  • chokidar:

    chokidar 代码示例

    const chokidar = require('chokidar');
    
    // 监视单个文件
    const watcher = chokidar.watch('file.txt', {
      persistent: true
    });
    
    watcher.on('change', (path) => {
      console.log(`File ${path} has been changed`);
    });
    
  • fsevents:

    fsevents 代码示例(仅限 macOS)

    const fsevents = require('fsevents');
    
    const stop = fsevents('path/to/dir', (path, flags, id) => {
      console.log(`File changed: ${path}`);
    });
    
    // 停止监视
    // stop();
    
  • gaze:

    gaze 代码示例

    const { Gaze } = require('gaze');
    
    // 监视目录中的所有文件
    const gaze = new Gaze('path/to/dir/**/*');
    
    gaze.on('all', (event, filepath) => {
      console.log(`File ${filepath} has been ${event}`);
    });
    
  • node-watch:

    node-watch 代码示例

    const watch = require('node-watch');
    
    // 监视文件或目录
    const watcher = watch('path/to/file_or_dir', { recursive: true }, (evt, name) => {
      console.log(`${name} has been ${evt}`);
    });
    
  • watch:

    watch 代码示例

    const watch = require('watch');
    
    // 监视目录
    watch.watchTree('path/to/dir', (f, curr, prev) => {
      if (typeof f === 'object' && prev === null && curr === null) {
        console.log('开始监视目录');
      } else if (prev === null) {
        console.log(`文件 ${f} 被创建`);
      } else if (curr.nlink === 0) {
        console.log(`文件 ${f} 被删除`);
      } else {
        console.log(`文件 ${f} 被修改`);
      }
    });
    

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

  • chokidar:

    选择 chokidar 如果你需要一个高性能、跨平台的文件监视库,支持递归监视目录,并且具有丰富的配置选项。它适合需要处理大量文件变化的应用,且对性能有较高要求。

  • fsevents:

    选择 fsevents 如果你主要在 macOS 平台上开发,并且需要利用 macOS 原生的文件系统事件 API 以获得更高效的监视性能。它适合对性能要求极高的应用,但平台限制较大。

  • gaze:

    选择 gaze 如果你需要一个简单易用的文件监视库,支持通配符和递归监视。它适合小型项目或需要快速实现文件监视功能的应用,但在性能和功能上不如 chokidar。

  • node-watch:

    选择 node-watch 如果你需要一个轻量级的文件监视库,具有简单的 API 和低资源消耗。它适合对资源使用敏感的应用,但功能相对简单。

  • watch:

    选择 watch 如果你需要一个功能全面的文件和目录监视库,支持递归监视和事件处理。它适合需要稳定和可靠监视功能的应用,但在性能和现代化方面可能不如其他库。

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.