This group of libraries handles file system interactions in Node.js environments, though they serve different primary purposes. chokidar, fsevents, gaze, node-watch, and watchpack are designed to detect file changes (watching), which is critical for build tools, dev servers, and sync scripts. fs-extra stands apart as a utility library that extends the native fs module with extra methods like ensureDir and copy, often used alongside watchers to manipulate files. Understanding the distinction between watching for changes and performing file operations is key to selecting the right tool.
When building Node.js tools, build systems, or dev servers, you often need to detect file changes or manipulate the file system reliably. The packages chokidar, fs-extra, fsevents, gaze, node-watch, and watchpack all touch the file system, but they solve different problems. Some watch for changes, while others modify files. Let's break down how they work and when to use each one.
The first distinction is whether the library watches for changes or performs actions on files.
chokidar, fsevents, gaze, node-watch, and watchpack are file watchers. They emit events when a file is created, changed, or deleted.
// chokidar: Watch for changes
const chokidar = require('chokidar');
const watcher = chokidar.watch('src/**/*.js');
watcher.on('change', path => console.log(`File ${path} changed`));
// fsevents: macOS native watching
const fsevents = require('fsevents');
const stop = fsevents.watch('src', (path, flags) => console.log(path, flags));
// gaze: Legacy glob-based watching
const { Gaze } = require('gaze');
const gaze = new Gaze('**/*.js');
gaze.on('changed', file => console.log(`${file} was changed`));
// node-watch: Pure JS watching
const watch = require('node-watch');
watch('src', { recursive: true }, (evt, name) => console.log(`${name} changed`));
// watchpack: Bundler-optimized watching
const Watchpack = require('watchpack');
const wp = new Watchpack({ aggregateTimeout: 1000 });
wp.watch({ files: [], directories: ['src'] });
wp.on('aggregated', (changes, removals) => console.log(changes));
fs-extra is a file utility. It does not watch files. It adds methods to copy, move, or ensure directories exist.
// fs-extra: File manipulation
const fs = require('fs-extra');
async function setup() {
await fs.ensureDir('dist/assets');
await fs.copy('src/assets', 'dist/assets');
}
File systems behave differently on Windows, macOS, and Linux. A good library hides these differences.
chokidar normalizes events across all OSs. It handles Windows file locking and macOS rename quirks automatically.
// chokidar: Works everywhere
const watcher = chokidar.watch('logs', { ignored: /(^|[\/\\])\../ });
// Handles Windows backslashes and macOS events uniformly
fsevents works only on macOS. Using it directly breaks your app on Windows or Linux.
// fsevents: macOS only
if (process.platform === 'darwin') {
const stop = fsevents.watch('.', log);
}
node-watch is pure JavaScript, so it runs everywhere, but it relies on polling or generic OS events which can be slower or less accurate than native bindings.
// node-watch: Cross-platform but generic
watch('.', { recursive: true }, (evt, name) => {
// Works on Windows, Linux, macOS without native deps
});
watchpack abstracts OS differences but is tuned for bundlers. It delays events to group them, which might feel laggy for interactive tools.
// watchpack: Aggregates events
wp.on('aggregated', (changes, removals) => {
// Receives batched updates rather than instant single events
});
gaze was cross-platform but struggled with performance on large trees in later years, leading to its decline.
// gaze: Legacy cross-platform
const gaze = new Gaze('**/*');
// Older implementation of cross-platform globbing
fs-extra is fully cross-platform for file operations, ensuring paths and permissions work consistently.
// fs-extra: Consistent file ops
await fs.move('./temp/file.txt', './final/file.txt');
// Handles permissions and paths across OSs
When watching thousands of files (like node_modules), performance matters.
watchpack is built for this. It aggregates changes and ignores deep trees unless specified.
// watchpack: Optimized for large trees
const wp = new Watchpack({
aggregateTimeout: 1000,
poll: false
});
wp.watch({ directories: ['node_modules'] });
chokidar is highly performant and uses fsevents on macOS automatically for speed.
// chokidar: Fast with native opts
const watcher = chokidar.watch('.', { usePolling: false });
// Uses native OS events where possible for speed
fsevents is the fastest on macOS because it is a native binding, but it lacks cross-platform support.
// fsevents: Native speed on macOS
const stop = fsevents.watch('.', log);
// Direct access to macOS FSEvents API
node-watch can use polling, which is CPU-intensive on large directories.
// node-watch: Polling option
watch('.', { recursive: true, poll: true }, callback);
// Polling consumes more CPU than native events
gaze often struggled with high file counts, leading to missed events or high memory usage in the past.
// gaze: Older performance profile
const gaze = new Gaze('**/*', { nodir: true });
// Known to have issues with very large file trees
fs-extra performance depends on the operation. copy is optimized but still synchronous in nature regarding I/O.
// fs-extra: I/O bound
await fs.copy('src', 'dist');
// Speed depends on disk I/O, not event handling
Some libraries offer rich features, while others stay minimal.
fs-extra provides the most helpful utility methods, like ensureDir which creates a directory if it doesn't exist.
// fs-extra: High-level utilities
await fs.ensureDir('/tmp/complex/path');
// Creates all intermediate directories automatically
chokidar offers a clean event emitter API with options for ignoring files.
// chokidar: Event emitter API
watcher.on('add', path => console.log(`File ${path} has been added`));
watcher.on('unlink', path => console.log(`File ${path} has been removed`));
node-watch uses a simple callback or promise style.
// node-watch: Callback style
watch('src', (evt, name) => console.log(name));
watchpack uses an aggregation model, which is different from standard event emitters.
// watchpack: Aggregated events
wp.on('aggregated', (changes, removals) => {
console.log(`${changes.length} files changed`);
});
gaze used a glob-centric API which was powerful but complex.
// gaze: Glob-centric
const gaze = new Gaze(['**/*.js', '!**/node_modules/**']);
fsevents provides raw event flags that require interpretation.
// fsevents: Raw flags
fsevents.watch('.', (path, flags) => {
// Flags indicate type of change (created, removed, etc.)
});
Maintenance status is critical for security and stability.
gaze is effectively deprecated. The repository is inactive, and it is not recommended for new projects.
// gaze: Do not use in new projects
// Considered legacy; use chokidar instead
fsevents is maintained but intended as a dependency for other tools, not direct usage.
// fsevents: Use via chokidar
// Direct usage limits you to macOS
chokidar, fs-extra, node-watch, and watchpack are actively maintained and safe for production.
// chokidar, fs-extra, node-watch, watchpack: Active
// Safe to install and use in 2024+
| Package | Type | Platform | Performance | Status |
|---|---|---|---|---|
chokidar | Watcher | All | High | ✅ Active |
fs-extra | Utility | All | N/A | ✅ Active |
fsevents | Watcher | macOS Only | Very High | ✅ Active (Native) |
gaze | Watcher | All | Low | ⚠️ Legacy |
node-watch | Watcher | All | Medium | ✅ Active |
watchpack | Watcher | All | High (Batched) | ✅ Active |
For 95% of use cases, choose chokidar. It is the industry standard for file watching, balancing performance, reliability, and cross-platform support. It is what powers Vite, Webpack, and many other major tools.
Use fs-extra alongside your watcher when you need to modify files. It makes tasks like copying assets or ensuring directories exist much simpler than using the native fs module.
Avoid gaze in new projects. It is outdated. Avoid direct use of fsevents unless you are writing a macOS-specific utility. Use watchpack only if you are building a bundler that needs to aggregate thousands of file events.
Final Thought: Stick to the tools that the ecosystem trusts. chokidar for watching and fs-extra for moving files will cover almost every need without introducing unnecessary risk.
Choose chokidar for most production applications requiring stable, cross-platform file watching. It abstracts away OS differences and handles edge cases like file renaming or permission errors gracefully. It is the default choice for major tools like Vite and Webpack, ensuring long-term support and community trust.
Choose fs-extra when you need reliable file manipulation methods that the native fs module lacks, such as ensureDir or recursive copy. It is not a watcher, so pair it with chokidar if you need to react to file changes. It is ideal for build scripts, installers, and CLI tools that modify the file system.
Choose fsevents only if you are building a macOS-specific tool and need the absolute lowest-level access to file events. For almost all other cases, rely on chokidar, which uses fsevents internally on macOS. Direct usage limits your application to Apple hardware and adds native compilation complexity.
Avoid gaze for new projects as it is considered legacy and no longer actively maintained. It was popular in the early Gulp ecosystem but has been superseded by more robust solutions like chokidar. Use it only if you are maintaining an older codebase that strictly depends on its specific globbing behavior.
Choose node-watch if you need a lightweight, pure JavaScript watcher without native dependencies. It is suitable for simple scripts or environments where installing native modules is problematic. However, it may not handle high-frequency events or complex file trees as efficiently as chokidar.
Choose watchpack if you are building a bundler or tool that needs to watch large directories like node_modules. It is optimized for aggregating events and delaying notifications to avoid overwhelming the system during massive file changes. It is less suitable for general-purpose application logic compared to chokidar.
Minimal and efficient cross-platform file watching library
There are many reasons to prefer Chokidar to raw fs.watch / fs.watchFile in 2026:
renameatomic option
awaitWriteFinish option
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.
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:persistent (default: true). Indicates whether the process
should continue to run as long as files are being watched.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.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.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.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.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.Check out third party chokidar-cli, which allows to execute a command on each change, or get a stdio stream of change events.
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 shellError: watch /home/ ENOSPCThere are two things that can cause it.
fs module used by chokidar: let fs = require('fs'); let grfs = require('graceful-fs'); grfs.gracefulify(fs);echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p.fs.watch
usePolling: true, which will switch backend to resource-intensive fs.watchFileAll fsevents-related issues (WARN optional dep failed, fsevents is not a constructor) are solved by upgrading to v4+.
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')));
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.
MIT (c) Paul Miller (https://paulmillr.com), see LICENSE file.