chokidar vs filewatcher vs gaze vs node-watch vs sane vs watch vs watchpack
File System Watching Strategies for Node.js Tooling
chokidarfilewatchergazenode-watchsanewatchwatchpackSimilar Packages:

File System Watching Strategies for Node.js Tooling

These libraries monitor file system changes to trigger builds, reload servers, or sync data. chokidar is the cross-platform standard, while watchpack targets bundlers. Older tools like watch and gaze offer legacy patterns but lack modern maintenance. node-watch provides a pure JavaScript alternative without native dependencies. sane and filewatcher serve niche historical roles but carry stability risks in current environments.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
chokidar012,254202 kB66 days agoMIT
filewatcher054-510 years agoMIT
gaze01,149-688 years agoMIT
node-watch034026.1 kB83 years agoMIT
sane0386-345 years agoMIT
watch01,282-5910 years agoApache-2.0
watchpack0403118 kB37 days agoMIT

File System Watching Strategies for Node.js Tooling

Monitoring file changes is a core requirement for development servers, build pipelines, and test runners. The packages chokidar, filewatcher, gaze, node-watch, sane, watch, and watchpack all solve this problem but differ significantly in stability, API design, and maintenance status. Let's break down how they handle common engineering challenges.

πŸ› οΈ Initialization & API Style

The way you start watching files varies from event emitters to callback-based systems. Understanding the setup helps you integrate them into your tooling.

chokidar uses an event emitter pattern that is familiar to most Node.js developers.

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

filewatcher requires creating an instance and adding files manually.

const fw = require('filewatcher')();
fw.add('src/main.js');
fw.add('src/utils.js');

gaze uses a callback function that returns the watcher instance.

const gaze = require('gaze');
gaze('src/**/*.js', function (err, watcher) {
  // watcher is ready
});

node-watch offers a simple function call that returns an emitter.

const watch = require('node-watch');
const watcher = watch('src', { recursive: true });

sane provides a standard watcher interface similar to chokidar.

const sane = require('sane');
const watcher = sane.watch('src');

watch uses a static method to create the watcher.

const watch = require('watch');
watch.watchCreate('src', function (err, files) {
  // setup complete
});

watchpack requires instantiating a class and passing configuration objects.

const Watchpack = require('watchpack');
const watcher = new Watchpack({
  aggregateTimeout: 1000
});

πŸ”” Event Handling & Change Detection

How you listen for changes determines how your build logic responds to file updates.

chokidar emits specific events like change, add, and unlink.

watcher.on('change', path => {
  console.log(`File ${path} changed`);
});

filewatcher triggers a single change event with the filename.

fw.on('change', function (filename) {
  console.log(`File ${filename} changed`);
});

gaze emits changed events within the callback context.

watcher.on('changed', function (file) {
  console.log(`File ${file} changed`);
});

node-watch passes the event type and filename to the callback.

watcher.on('update', function (evt, name) {
  console.log(`File ${name} changed`);
});

sane emits change events with the file path and root.

watcher.on('change', function (filePath, root) {
  console.log(`File ${filePath} changed`);
});

watch passes the event type and filename to the callback.

watch.watchMonitor('src', function (event, filename) {
  console.log(`File ${filename} ${event}`);
});

watchpack aggregates events and fires a single aggregated callback.

watcher.watch({ files: ['src/index.js'], directories: [] });
watcher.on('aggregated', function (changes, removals) {
  console.log(`Changes: ${changes}`);
});

🌐 Globbing & Pattern Matching

Selecting which files to watch is critical for performance and correctness.

chokidar supports glob patterns directly in the watch path.

chokidar.watch('src/**/*.js', { ignored: /node_modules/ });

filewatcher does not support globs natively; you must resolve paths yourself.

// Must manually resolve files before adding
const files = resolveFiles('src');
files.forEach(f => fw.add(f));

gaze was built specifically for globbing support.

gaze('**/*.js', { cwd: 'src' }, function (err, watcher) {
  // Watches all JS files
});

node-watch supports filtering via options but not full globs in path.

watch('src', {
  filter: name => /\.js$/.test(name)
});

sane supports ignoring patterns via configuration.

sane.watch('src', { glob: ['**/*.js'] });

watch requires manual filtering or external glob libraries.

// No built-in glob support in base API
watch.watchTree('src', function (f, curr, prev) {
  if (/\.js$/.test(f)) { /* handle */ }
});

watchpack handles patterns through the files/directories configuration.

watcher.watch({ 
  files: ['src/index.js'], 
  directories: ['src/components'] 
});

⚠️ Maintenance & Stability Status

Choosing a library with active maintenance prevents future breakage during Node upgrades.

chokidar is actively maintained and the industry standard.

  • βœ… Safe for production use.
  • βœ… Handles native OS quirks automatically.

filewatcher relies on native C++ bindings.

  • ❌ Risk of breakage on Node version upgrades.
  • ❌ Harder to install in restricted environments.

gaze is stable but less active than chokidar.

  • ⚠️ Use only if globbing logic is tightly coupled.
  • ⚠️ Consider migrating to chokidar for long-term health.

node-watch is pure JavaScript and stable.

  • βœ… Good for simple use cases.
  • βœ… No compilation steps required.

sane is largely legacy within the Jest ecosystem.

  • ❌ Superseded by jest-haste-map.
  • ❌ Not recommended for general tooling.

watch is officially deprecated.

  • ❌ Do not use in new projects.
  • ❌ npm directs users to chokidar.

watchpack is maintained by the Webpack team.

  • βœ… Safe for bundler development.
  • ⚠️ Overkill for simple task runners.

πŸ“Š Summary Table

PackageMaintenanceNative DepsGlob SupportEvent Aggregation
chokidarβœ… Active❌ Noβœ… Yes❌ No
filewatcher⚠️ Lowβœ… Yes❌ No❌ No
gaze⚠️ Low❌ Noβœ… Yes❌ No
node-watchβœ… Active❌ No⚠️ Filter Only❌ No
sane❌ Legacy❌ Noβœ… Yes❌ No
watch❌ Deprecated❌ No❌ No❌ No
watchpackβœ… Active❌ No⚠️ Config Basedβœ… Yes

πŸ’‘ Final Recommendation

For most frontend tooling tasks β€” such as hot reloading or build triggers β€” chokidar is the clear choice. It balances feature richness with stability and avoids the pitfalls of native bindings. Use watchpack only if you are building a bundler that needs to batch file events for performance. Avoid watch and sane in new projects due to deprecation and legacy status. If you need a pure JavaScript solution without extra dependencies, node-watch is a solid fallback. Always prioritize libraries with active maintenance to ensure compatibility with future Node.js versions.

How to Choose: chokidar vs filewatcher vs gaze vs node-watch vs sane vs watch vs watchpack

  • chokidar:

    Choose chokidar for most production tooling needs like dev servers or build watchers. It offers consistent behavior across Windows, macOS, and Linux without native bindings. The API is stable, well-documented, and handles edge cases like file renaming reliably.

  • filewatcher:

    Avoid filewatcher for new projects unless you have a specific need for its native C++ bindings. The reliance on compiled modules often causes installation failures across different Node versions or CI environments. Modern pure JavaScript alternatives provide better stability.

  • gaze:

    Choose gaze only if you are maintaining legacy codebases that depend on its specific globbing implementation. It supports file patterns out of the box, which chokidar also handles via glob options. New projects should prefer chokidar for better long-term support.

  • node-watch:

    Choose node-watch if you need a lightweight solution without any native dependencies or external requirements. It is written in pure JavaScript and works well for simple recursive watching tasks. However, it may lack some advanced features found in chokidar.

  • sane:

    Avoid sane for new general-purpose tooling as it is largely superseded by jest-haste-map within the Jest ecosystem. It was designed for specific performance needs in testing environments rather than general file watching. Modern alternatives offer better maintenance and community support.

  • watch:

    Do not use watch in new projects as it is officially deprecated and unmaintained. The npm page explicitly directs users to migrate to chokidar for better cross-platform support. Continuing to use it introduces unnecessary risk and technical debt.

  • watchpack:

    Choose watchpack if you are building a module bundler similar to Webpack that requires event aggregation. It delays events to batch changes together, which reduces rebuild thrashing during massive file saves. It is specialized for high-performance bundling pipelines rather than general task running.

README for chokidar

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.