chokidar-cli vs grunt-contrib-watch vs gulp-watch vs nodemon vs onchange vs watch
File Watching and Process Restarting Tools in Node.js Development
chokidar-cligrunt-contrib-watchgulp-watchnodemononchangewatchSimilar Packages:

File Watching and Process Restarting Tools in Node.js Development

chokidar-cli, grunt-contrib-watch, gulp-watch, nodemon, onchange, and watch are all npm packages designed to monitor file system changes during development and trigger actions such as restarting a server, rebuilding assets, or running tests. These tools help automate repetitive tasks by reacting to file modifications, additions, or deletions. While they share the common goal of improving developer workflow through file watching, they differ significantly in their integration points, configuration models, underlying libraries, and target use cases — ranging from general-purpose CLI watchers to tightly coupled task runner plugins or specialized Node.js process monitors.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
chokidar-cli00-05 years agoMIT
grunt-contrib-watch01,967-1268 years agoMIT
gulp-watch0637-708 years agoMIT
nodemon026,688219 kB123 months agoMIT
onchange0828-66 years agoMIT
watch01,281-599 years agoApache-2.0

File Watching in Practice: Choosing the Right Tool for Your Workflow

When you're building JavaScript applications, you often need something to notice when your files change and then do something useful—like restarting your server, recompiling code, or running tests. The six packages here (chokidar-cli, grunt-contrib-watch, gulp-watch, nodemon, onchange, and watch) all solve variations of this problem, but they’re built for different contexts, levels of complexity, and tooling ecosystems. Let’s break down how they really work—and when to use which.

🔍 Core Purpose and Integration Model

Each tool fits into a specific layer of the development stack:

  • nodemon is a Node.js process manager—it watches files and restarts your app.
  • chokidar-cli and onchange are general-purpose CLI watchers—they run shell commands when files change.
  • gulp-watch and grunt-contrib-watch are task runner plugins—they only work inside Gulp or Grunt pipelines.
  • watch is a barebones library—it gives you raw file events with minimal abstraction.

This distinction matters because it dictates whether you can use the tool standalone or if it forces you into a particular build system.

Code Examples: Basic Watch Setup

Here’s how each package handles a simple task: run npm test whenever a .js file changes.

# chokidar-cli
npx chokidar "src/**/*.js" -c "npm test"
# onchange
npx onchange "src/**/*.js" -- npm test
// gulp-watch (requires gulpfile.js)
const gulp = require('gulp');
const watch = require('gulp-watch');

gulp.task('default', () => {
  watch('src/**/*.js', () => gulp.src('src').pipe(/* run tests */));
});
// grunt-contrib-watch (requires Gruntfile.js)
module.exports = function(grunt) {
  grunt.initConfig({
    watch: {
      scripts: {
        files: ['src/**/*.js'],
        tasks: ['exec:test']
      }
    },
    exec: {
      test: { cmd: 'npm test' }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-exec');
};
# nodemon (not ideal for tests, but possible)
npx nodemon --watch src --ext js --exec "npm test"
// watch (low-level, no glob support)
const watch = require('watch');

watch.watchTree('./src', (f, curr, prev) => {
  if (typeof f === 'string' && f.endsWith('.js')) {
    require('child_process').exec('npm test');
  }
});

💡 Note: watch doesn’t support glob patterns—you’d need to walk directories manually or use another library.

⚙️ Underlying File Watching Engine

Most modern tools rely on chokidar, a battle-tested file watcher that normalizes behavior across macOS, Linux, and Windows and handles edge cases like network drives and symlink loops.

  • Uses chokidar: chokidar-cli, gulp-watch, onchange
  • Uses custom logic (based on fs.watch): nodemon, grunt-contrib-watch, watch

This has real implications:

  • chokidar-based tools generally offer better reliability, glob pattern support, and cross-platform consistency.
  • nodemon implements its own watcher but includes workarounds for common fs.watch pitfalls and is highly optimized for Node.js restart scenarios.
  • The original watch package uses raw fs.watchFile/fs.watch, which can be slow (polling-based) and miss events on some systems.

🛑 Maintenance and Deprecation Status

As of 2024:

  • grunt-contrib-watch is effectively deprecated. Grunt’s ecosystem is largely unmaintained, and this plugin hasn’t had meaningful updates in years. Do not use in new projects.
  • watch (by Ryan Dahl) is archived and unmaintained. Its GitHub repo is read-only, and it lacks modern features. Avoid for production tooling.
  • The others (chokidar-cli, gulp-watch, nodemon, onchange) are actively maintained with recent releases and issue triage.

🎯 Specialized Use Cases

Restarting a Node.js Server

If you’re developing an Express, Fastify, or Koa app, nodemon is the clear winner:

# Standard nodemon usage
npx nodemon server.js

It handles process signals correctly, preserves stdin/stdout, supports delay before restart (--delay), and respects .nodemonignore. None of the general-purpose CLI tools match this level of integration.

Running Shell Commands with Glob Support

For arbitrary commands (e.g., tsc --build, eslint ., jest), both chokidar-cli and onchange work well:

# onchange: simpler syntax, runs on first change by default
onchange "src/**/*.{ts,tsx}" -- tsc --noEmit

# chokidar-cli: more explicit flags
chokidar "src/**/*.{ts,tsx}" -c "tsc --noEmit" --initial

Key difference: onchange runs the command immediately on startup (unless --no-initial is used), while chokidar-cli requires --initial to do the same.

Integration with Build Pipelines

If you’re already using Gulp, gulp-watch lets you plug file watching directly into your stream pipeline:

const gulp = require('gulp');
const watch = require('gulp-watch');
const babel = require('gulp-babel');

gulp.task('scripts', () => {
  return gulp.src('src/*.js')
    .pipe(babel())
    .pipe(gulp.dest('dist'));
});

gulp.task('watch', () => {
  watch('src/*.js', gulp.series('scripts'));
});

This avoids spawning external processes and keeps everything in-memory. But if you’re not using Gulp, this adds unnecessary complexity.

🧪 Error Handling and Reliability

  • nodemon will keep trying to restart your app even if it crashes on launch—it won’t quit after one failure.
  • onchange and chokidar-cli will continue watching after command failures; they don’t treat exit codes as fatal.
  • grunt-contrib-watch halts on task errors unless configured otherwise.
  • watch provides no error handling—you must wrap callbacks in try/catch.

📋 Feature Comparison Table

PackageStandalone CLI?Glob Patterns?Runs Shell Commands?Task Runner Plugin?Actively Maintained?Best For
chokidar-cliCustom CLI automation with precise control
grunt-contrib-watch❌ (runs Grunt tasks)✅ (Grunt)Legacy Grunt projects only
gulp-watch❌ (uses Gulp streams)✅ (Gulp)Gulp-based asset pipelines
nodemon✅ (via --watch)✅ (--exec)Restarting Node.js apps
onchangeSimple, zero-config command running
watch❌ (callback only)Learning or trivial scripts

💡 Final Recommendations

  • Building a Node.js backend? → Use nodemon. It’s purpose-built, reliable, and universally understood by Node developers.
  • Need to run shell commands on file changes? → Pick onchange for simplicity or chokidar-cli for more flags and control.
  • Stuck in a Gulp project?gulp-watch is your best bet for tight integration.
  • Working on old Grunt code? → Keep grunt-contrib-watch only until you can migrate away.
  • Starting fresh? → Avoid watch entirely—modern alternatives are safer and more capable.

The right choice isn’t about which tool is “best” overall—it’s about matching the tool to your project’s architecture, team conventions, and maintenance horizon. In 2024, that usually means leaning toward nodemon, onchange, or chokidar-cli for new work, and treating the others as legacy compatibility layers.

How to Choose: chokidar-cli vs grunt-contrib-watch vs gulp-watch vs nodemon vs onchange vs watch

  • chokidar-cli:

    Choose chokidar-cli when you need a lightweight, standalone command-line tool that wraps the robust chokidar file watcher with minimal overhead. It’s ideal for shell scripts, simple automation tasks, or environments where you want fine-grained control over glob patterns and events without tying into a larger build system. Avoid it if you require deep integration with task runners like Grunt or Gulp.

  • grunt-contrib-watch:

    Choose grunt-contrib-watch only if you’re maintaining a legacy project built on Grunt and already using its ecosystem. This plugin is tightly coupled to Grunt’s task model and lifecycle hooks. It should not be used in new projects, as Grunt itself has seen minimal active development in recent years and lacks modern DX features like efficient rebuilds or native ES module support.

  • gulp-watch:

    Choose gulp-watch if your build pipeline is based on Gulp and you want seamless integration with Gulp streams and tasks. It leverages chokidar under the hood and works well within Gulp’s functional, stream-based architecture. However, avoid it for non-Gulp projects, as it offers no standalone CLI and requires Gulp’s runtime to function.

  • nodemon:

    Choose nodemon when your primary goal is to automatically restart a Node.js application during development whenever source files change. It’s purpose-built for this scenario, supports ignore/include rules, delay tuning, and environment variable inheritance. It’s the de facto standard for Node.js server reloading and integrates smoothly with debuggers and cluster modes.

  • onchange:

    Choose onchange when you need a zero-config, cross-platform CLI watcher that runs arbitrary shell commands in response to file changes. It uses chokidar internally and supports glob patterns, debounce delays, and initial execution. It’s excellent for simple scripts, monorepo tooling, or replacing custom watch scripts without pulling in a full task runner.

  • watch:

    Choose the watch package (by Ryan Dahl) only for very basic use cases or educational purposes. It’s a minimal, callback-based file watcher with no glob support, limited event granularity, and no active maintenance. It lacks features expected in modern workflows and should be avoided in production-grade tooling in favor of chokidar-based alternatives.

README for chokidar-cli

Chokidar CLI

Build Status

Fast cross-platform command line utility to watch file system changes.

The underlying watch library is Chokidar, which is one of the best watch utilities for Node. Chokidar is battle-tested:

It is used in brunch, gulp, karma, PM2, browserify, webpack, BrowserSync, socketstream, derby, and many others. It has proven itself in production environments.

Prerequisites

  • Node.js v8.10.0 or newer

Install

If you need it only with npm scripts:

npm install chokidar-cli

Or globally

npm install -g chokidar-cli

Usage

Chokidar can be invoked using the chokidar command, without the -cli suffix.

Arguments use the form of runtime flags with string parameters, delimited by quotes. While in principal both single and double quotes are supported by chokidar-cli, the actual command line argument parsing is dependent on the operating system and shell used; for cross-platform compatibility, use double quotes (with escaping, if necessary), as single quotes are not universally supported by all operating systems.

This is particularly important when using chokidar-cli for run scripts specified in package.json. For maximum platform compatibility, make sure to use escaped double quotes around chokidar's parameters:

"run": {
  "chokidar": "chokidar \"**/*.js\" -c \"...\""
},

Default behavior

By default chokidar streams changes for all patterns to stdout:

$ chokidar "**/*.js" "**/*.less"
change:test/dir/a.js
change:test/dir/a.less
add:test/b.js
unlink:test/b.js

Each change is represented with format event:relativepath. Possible events: add, unlink, addDir, unlinkDir, change.

Output only relative paths on each change

$ chokidar "**/*.js" "**/*.less" | cut -d ":" -f 2-
test/dir/a.js
test/dir/a.less
test/b.js
test/b.js

Run npm run build-js whenever any .js file changes in the current work directory tree

chokidar "**/*.js" -c "npm run build-js"

Watching in network directories must use polling

chokidar "**/*.less" -c "npm run build-less" --polling

Pass the path and event details in to your custom command

chokidar "**/*.less" -c "if [ '{event}' = 'change' ]; then npm run build-less -- {path}; fi;"

Detailed help

Usage: chokidar <pattern> [<pattern>...] [options]

<pattern>:
Glob pattern to specify files to be watched.
Multiple patterns can be watched by separating patterns with spaces.
To prevent shell globbing, write pattern inside quotes.
Guide to globs: https://github.com/isaacs/node-glob#glob-primer


Options:
  -c, --command           Command to run after each change. Needs to be
                          surrounded with quotes when command contains spaces.
                          Instances of `{path}` or `{event}` within the command
                          will be replaced by the corresponding values from the
                          chokidar event.
  -d, --debounce          Debounce timeout in ms for executing command
                                                                  [default: 400]
  -t, --throttle          Throttle timeout in ms for executing command
                                                                  [default: 0]
  -s, --follow-symlinks   When not set, only the symlinks themselves will be
                          watched for changes instead of following the link
                          references and bubbling events through the links path
                                                      [boolean] [default: false]
  -i, --ignore            Pattern for files which should be ignored. Needs to be
                          surrounded with quotes to prevent shell globbing. The
                          whole relative or absolute path is tested, not just
                          filename. Supports glob patterns or regexes using
                          format: /yourmatch/i
  --initial               When set, command is initially run once
                                                      [boolean] [default: false]
  -p, --polling           Whether to use fs.watchFile(backed by polling) instead
                          of fs.watch. This might lead to high CPU utilization.
                          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         [boolean] [default: false]
  --poll-interval         Interval of file system polling. Effective when --
                          polling is set                          [default: 100]
  --poll-interval-binary  Interval of file system polling for binary files.
                          Effective when --polling is set         [default: 300]
  --verbose               When set, output is more verbose and human readable.
                                                      [boolean] [default: false]
  --silent                When set, internal messages of chokidar-cli won't be
                          written.                    [boolean] [default: false]
  -h, --help              Show help                                    [boolean]
  -v, --version           Show version number                          [boolean]

Examples:
  chokidar "**/*.js" -c "npm run build-js"  build when any .js file changes
  chokidar "**/*.js" "**/*.less"            output changes of .js and .less
                                            files

License

MIT