Skip to content

Guide · Open source

How to use chokidar: watch files in Node.js and react to changes

Updated · written with AI from the project's own documentation and checked against our catalogue data

Chokidar is a minimal, cross-platform file watching library for Node.js, written in TypeScript and released under the MIT licence. It exists because raw fs.watch reports changes inconsistently across operating systems, so Chokidar gives you normalized add, change and unlink events. This guide shows you how to install it, start a watcher, filter what gets watched and handle editor saves and large writes.

Chokidarpaulmillr/chokidar · ★ 12.3k · MIT

Quick start

  1. 1Install the package. Run npm install chokidar in your Node.js project folder.
  2. 2Import chokidar. Use import chokidar from 'chokidar' or const chokidar = require('chokidar') depending on your module setup.
  3. 3Start watching a path. Call chokidar.watch with a file or directory path and attach an 'all' or specific event listener.
  4. 4Add filters. Set ignored, depth and ignoreInitial so only the files you need are watched.
  5. 5Handle events. Attach listeners for add, change, unlink and error to run your build or script step.
  6. 6Tune for editors or large files. Enable atomic or awaitWriteFinish if your editor or writes cause duplicate or early events.
  7. 7Close when finished. Call await watcher.close() to stop watching; create a new watcher if you need to start again.

What does chokidar do and when should you use it?

Chokidar watches files and directories for changes. Raw fs.watch can report one change as a non-transparent rename, can fire twice for a single change, and behaves differently for recursive watching on each platform. Chokidar normalizes these cases into add, change and unlink events, plus addDir and unlinkDir for directories.

Developers typically use it inside build tools, dev servers and scripts that need to rerun work when files change.

  • Good fit: Node.js build tools or dev servers that rerun work on file changes
  • Good fit: teams that need consistent file events across macOS, Windows and Linux
  • Good fit: projects watching network or unusual filesystems that can accept higher CPU use via polling
  • Not a fit: non-JavaScript projects, since it is a Node.js library
  • Not a fit: one-off file checks instead of ongoing watching

Install chokidar with npm

Chokidar is installed through a package manager. The only prerequisite listed is Node.js. Run the npm command below in your project folder.

npm install chokidar

Start a basic watcher

Import the library and call watch with a path. Files are watched, and directories are watched recursively. The 'all' event receives the event name and the path. The library can be imported as an ES module or with require, as shown in the README.

  • ES module: import chokidar from 'chokidar';
  • Named import: import { watch } from 'chokidar';
  • CommonJS: const chokidar = require('chokidar');
chokidar.watch('src').on('all', (event, path) => console.log(event, path));

Listen for specific events and filter what is watched

Use separate listeners for add, change, unlink, ready and error when you need different behaviour for each. The ignored option accepts strings (exact paths, not globs), RegExp objects tested against the whole path with forward slashes, functions, or objects with a path and recursive flag. Set ignoreInitial to true to skip add events for files found during the initial scan.

Scope watches tightly. Chokidar watches everything under the paths you pass, so use ignored and depth rather than watching more than you need.

  • ignored: /(^|\/)\../ ignores dotfiles
  • ignored: /\/node_modules\// ignores node_modules
  • depth: limits how many subdirectory levels are traversed; Infinity means unlimited
  • cwd: sets the base directory that paths are resolved against
const watcher = chokidar.watch('src', { ignored: [ /(^|\/)\../, // dotfiles (path, stats) => stats?.isFile() && !path.endsWith('.js'), // only .js files ], ignoreInitial: true, }); 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));

Add and remove paths while the watcher runs

The watcher object has methods to change what it watches. add starts watching more files or directories. unwatch stops watching paths synchronously, and they stay ignored until added again. getWatched returns the watched directories and the entry names inside each.

  • .add(paths) starts watching more files or directories
  • Synchronous .unwatch(paths) stops watching paths
  • getWatched() returns an object of directories and their entries
watcher.add(['lib', 'index.js']); watcher.unwatch('lib'); console.log(watcher.getWatched());

Handle editor saves, large writes and unusual filesystems

Some editors save through a temp file and rename it, which produces unlink then add. With atomic enabled, Chokidar emits a single change within a window of 100 ms by default. For large or chunked writes, awaitWriteFinish holds add and change events until the file size stays constant for a set stability threshold. Higher thresholds are safer but less responsive, and the right value depends on the OS and hardware.

On network or unusual filesystems where fs.watch is unreliable, use the polling backend. It uses more CPU, and an in-place write that changes none of size, modification time, existence or (except on Windows) inode is not detected.

  • atomic: true by default with native backends; false with polling
  • awaitWriteFinish: { stabilityThreshold: 2000, pollInterval: 100 }
  • backend: 'polling' with pollingInterval: 100 by default
  • CHOKIDAR_USEPOLLING env var forces polling on or off, even if code sets backend
chokidar.watch('uploads', { awaitWriteFinish: { stabilityThreshold: 2000, pollInterval: 100 }, atomic: 100, }); chokidar.watch('/mnt/nfs/data', { backend: 'polling', pollingInterval: 500 });

Close the watcher cleanly

Call close to stop the watcher. It is async and terminal: it removes all listeners, and once closing has started, add throws. Repeated calls return the same Promise. To resume watching, create a new watcher.

await watcher.close();

What people use it for

  • Rerunning a build step when source files in src change
  • Triggering a dev server reload when template or script files are saved
  • Waiting for large uploads to finish before processing them with awaitWriteFinish
  • Watching an NFS-mounted data folder with the polling backend
  • Logging which files were added or removed in a project folder

Frequently asked questions

How do I install chokidar?

Install it from npm with npm install chokidar. The README lists Node.js as the prerequisite, and you import it with import chokidar from 'chokidar' or require it.

Is chokidar free to use?

Chokidar is released under the MIT licence, as stated in the project's details. Check the LICENSE file in the repository for the full terms.

What is the difference between chokidar and fs.watch?

fs.watch is Node's built-in API, which the README describes as reporting changes inconsistently across platforms. Chokidar uses native fs.watch by default but normalizes add, change and unlink events, deduplicates them and handles recursive watching on each platform.

Why does chokidar emit a change instead of unlink and add when I save a file?

Editors that save via a temp file and rename produce unlink then add. The atomic option, enabled by default with native backends, merges these into one change within 100 ms by default.

Why is chokidar missing changes on my network drive?

Native fs.watch can be unreliable on network and unusual filesystems. Set backend to 'polling', which is stat-based and uses more CPU, but note that in-place writes which change none of size, modification time, existence or inode are not detected.

Does chokidar support glob patterns?

No. The README says globs are not supported in the ignored option; string matchers are exact paths, and RegExp or function matchers are the alternatives.

New agent skills, repos and AI tools — every week

The best new skills and open-source projects, the fastest-growing repos, and one free prompt. Five minutes to read. Unsubscribe anytime.

Our verdict

Chokidar is a good choice if you are building a Node.js build tool, dev server or script that must react to file changes consistently across macOS, Windows and Linux. Scope your watches with ignored and depth, since it watches everything under the paths you give it. If you only need a one-time file check, are working outside Node.js, or need a dedicated CLI restart tool, consider the comparable projects listed, such as nodemon or fs.watch.

Install options & downloads