nodemon vs watch vs chokidar-cli vs grunt-contrib-watch vs onchange vs gulp-watch
文件系统监听工具在前端开发中的选型对比
nodemonwatchchokidar-cligrunt-contrib-watchonchangegulp-watch类似的npm包:
文件系统监听工具在前端开发中的选型对比

chokidar-cligrunt-contrib-watchgulp-watchnodemononchangewatch 都是用于监听文件系统变化并触发相应操作的 Node.js 工具,广泛应用于开发流程自动化(如热重载、构建、测试等)。它们基于底层文件监听库(如 chokidar 或 fs.watch),但面向不同使用场景和构建体系:nodemon 专为重启 Node.js 应用设计;grunt-contrib-watchgulp-watch 分别集成于 Grunt 和 Gulp 构建生态;而 chokidar-clionchangewatch 则提供更通用的命令行接口,适用于任意 shell 命令的触发。这些工具在配置方式、性能表现、跨平台兼容性及与现代工具链的集成能力上存在显著差异。

npm下载趋势
3 年
GitHub Stars 排名
统计详情
npm包名称
下载量
Stars
大小
Issues
发布时间
License
nodemon8,459,35226,680219 kB112 个月前MIT
watch653,4521,281-599 年前Apache-2.0
chokidar-cli414,2490-04 年前MIT
grunt-contrib-watch328,6691,974-1278 年前MIT
onchange209,970829-65 年前MIT
gulp-watch132,446639-707 年前MIT

文件监听工具深度对比:chokidar-cli、grunt-contrib-watch、gulp-watch、nodemon、onchange 与 watch

在前端工程化中,监听文件变化并自动触发构建、测试或重启是提升开发效率的核心环节。虽然这些工具表面功能相似,但它们的设计目标、适用场景和技术实现差异巨大。本文从真实开发痛点出发,深入比较六款主流监听工具的技术细节,帮助你做出精准选型。

🛠️ 核心用途与定位差异

首先明确:这些工具并非彼此替代关系,而是服务于不同技术栈和工作流。

  • nodemonNode.js 进程管理器,专为重启服务设计。
  • grunt-contrib-watchgulp-watch构建系统插件,分别绑定 Grunt 和 Gulp。
  • chokidar-clionchangewatch通用命令行监听器,可触发任意 shell 命令。

💡 关键洞察:如果你的项目不使用 Grunt/Gulp,就不要为了监听文件而引入整个构建系统。

🔍 监听引擎与跨平台可靠性

底层监听机制直接影响稳定性和性能。

  • chokidar-cligulp-watch(v5+)和 onchange 均基于 chokidar —— 它封装了 fs.watchfsevents(macOS)和轮询机制,在所有平台提供一致行为,能正确处理符号链接、大目录和网络驱动器。
  • watch 直接使用 Node.js 原生 fs.watch,在 macOS 和 Windows 上存在已知问题(如子目录监听失效、事件重复触发)。
  • nodemon 内部使用 chokidar(自 v2.0 起),确保高可靠性。
  • grunt-contrib-watch 默认使用 gaze(已归档),虽可切换至 chokidar,但配置复杂且社区支持弱。

代码示例:监听 src 目录下的 JS 文件变更

# chokidar-cli(可靠,支持 glob)
npx chokidar 'src/**/*.js' -c 'echo "Changed: {path}"'

# onchange(简洁,跨平台稳定)
npx onchange 'src/**/*.js' -- echo "Changed"

# watch(可能漏报或重复,不推荐生产使用)
npx watch 'echo Changed' src

# nodemon(仅用于重启 Node 进程)
npx nodemon --watch src --exec 'node server.js'

# gulp-watch(需在 Gulpfile 中使用)
const watch = require('gulp-watch');
gulp.task('dev', () => {
  watch('src/**/*.js', () => gulp.src('src').pipe(...));
});

# grunt-contrib-watch(需 Gruntfile 配置)
grunt.initConfig({
  watch: {
    scripts: {
      files: ['src/**/*.js'],
      tasks: ['babel']
    }
  }
});

⚙️ 高级功能对比:延迟、过滤与事件类型

真实开发中,你常需要避免频繁触发(如保存时多次写入)或仅响应特定事件(如新增文件)。

功能chokidar-clionchangewatchnodemongulp-watchgrunt-contrib-watch
防抖/延迟-d, --debounce--delay.pipe(wait())options: { debounceDelay }
仅监听 add 事件-a, --add{ events: ['add'] }
忽略 node_modules✅ 默认忽略✅ 默认忽略❌ 需手动排除✅ 默认忽略✅ 可配置✅ 可配置
传递文件路径{path} 占位符{changed}✅ Vinyl 对象

代码示例:仅在新增 .test.js 文件时运行测试

# chokidar-cli 支持事件过滤
npx chokidar 'src/**/*.test.js' -a -c 'npm test {path}'

# onchange 无法区分事件类型,会响应所有变更
npx onchange 'src/**/*.test.js' -- npm test

# gulp-watch 可指定事件
watch('src/**/*.test.js', { events: ['add'] }, (vinyl) => {
  // vinyl.path 包含完整路径
  runTests(vinyl.path);
});

🧩 与现代前端工具链集成

在 Vite、Webpack 或 Turbopack 主导的今天,监听工具的角色正在演变。

  • nodemon 仍是后端开发首选,常与前端 dev server 并行运行:

    // package.json
    "scripts": {
      "dev": "concurrently \"vite\" \"nodemon server/index.js\""
    }
    
  • 通用 CLI 工具(如 chokidar-clionchange)适合补充现代工具链的盲区,例如:

    • 监听非 JS/CSS 资源(如 Markdown、JSON 配置)
    • 触发非构建类命令(如生成类型定义、同步静态资源)
    # 监听 content 目录生成静态站点
    npx onchange 'content/**/*' -- eleventy
    
  • Grunt/Gulp 插件 在新项目中已无必要。现代 bundler(如 Webpack 的 watchOptions、Vite 的 HMR)内置高效监听,无需额外插件。

⚠️ 维护状态与弃用风险

  • grunt-contrib-watch:Grunt 生态已停滞,该插件最后一次主要更新在 2018 年。新项目绝对不要使用
  • watch:虽仍可安装,但长期未更新,且依赖不可靠的 fs.watch仅限临时脚本
  • 其余工具(chokidar-cligulp-watchnodemononchange)均活跃维护,兼容 Node.js LTS 版本。

📊 选型决策树

根据你的具体场景快速判断:

  1. 是否在开发 Node.js 服务? → 用 nodemon
  2. 是否使用 Gulp 构建? → 用 gulp-watch
  3. 是否维护老旧 Grunt 项目? → 用 grunt-contrib-watch(但计划迁移)
  4. 需要通用、可靠的 CLI 监听器? → 优先 chokidar-cli(功能全)或 onchange(语法简)
  5. 只是临时调试小脚本? → 可用 watch,但别用于正式项目

💎 总结:没有“最好”,只有“最合适”

  • 追求最大兼容性与控制力chokidar-cli 是通用场景的首选,尤其当你需要事件过滤或延迟执行。
  • 喜欢极简命令行体验onchange 的语法更接近自然语言,适合快速编写 npm scripts。
  • 专注 Node.js 后端开发nodemon 提供开箱即用的智能重启,无可替代。
  • 深陷 Grunt/Gulp 生态:按构建系统选择对应插件,但应制定迁移计划。
  • 避免踩坑:永远不要在新项目中使用 watchgrunt-contrib-watch

最终,工具的价值在于解决实际问题。理解每个工具的设计边界,才能避免“用大炮打蚊子”或“用螺丝刀砍树”的工程陷阱。

如何选择: nodemon vs watch vs chokidar-cli vs grunt-contrib-watch vs onchange vs gulp-watch
  • nodemon:

    选择 nodemon 如果你开发的是 Node.js 后端服务或 CLI 工具,需要在代码变更时自动重启进程。它内置智能忽略规则(如 node_modules)、支持配置文件和信号控制,是 Node.js 开发的事实标准。但它不适合前端资源构建或通用文件监听场景。

  • watch:

    选择 watch 如果你需要最简化的监听逻辑且对性能要求不高。它基于原生 fs.watch,API 极简(watch 'command' 'dir'),但跨平台稳定性较差(尤其在 macOS 和 Windows 上可能出现重复事件或漏报)。仅建议用于简单脚本或临时调试,生产级项目应优先考虑基于 chokidar 的方案。

  • chokidar-cli:

    选择 chokidar-cli 如果你需要一个轻量、灵活且基于 chokidar 的命令行监听器,支持 glob 模式、延迟执行和精确的事件过滤(如仅 on-add)。它不绑定特定构建系统,适合在 npm scripts 中直接调用任意命令,尤其适用于需要精细控制监听行为的现代前端项目。

  • grunt-contrib-watch:

    选择 grunt-contrib-watch 仅当你仍在维护基于 Grunt 的旧项目。该插件深度集成 Grunt 任务系统,支持 livereload 和任务依赖,但 Grunt 生态已基本被 Webpack、Vite 等现代工具取代。新项目应避免引入 Grunt 及其相关插件。

  • onchange:

    选择 onchange 如果你偏好简洁的命令行语法、支持通配符路径和跨平台 shell 命令执行。它的 API 直观(类似 onchange 'src/**/*' -- npm run build),启动快,适合集成到 npm scripts 中。但功能相对基础,缺乏高级过滤或延迟控制选项。

  • gulp-watch:

    选择 gulp-watch 如果你的构建流程完全基于 Gulp 且需要流式(stream-based)文件处理。它返回 Vinyl 文件对象流,可无缝接入 Gulp 管道,但若项目未使用 Gulp,则引入它会带来不必要的复杂性。对于非 Gulp 项目,更简单的 CLI 工具是更好选择。

nodemon的README

Nodemon Logo

nodemon

nodemon is a tool that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected.

nodemon does not require any additional changes to your code or method of development. nodemon is a replacement wrapper for node. To use nodemon, replace the word node on the command line when executing your script.

NPM version Backers on Open Collective Sponsors on Open Collective

Installation

Either through cloning with git or by using npm (the recommended way):

npm install -g nodemon # or using yarn: yarn global add nodemon

And nodemon will be installed globally to your system path.

You can also install nodemon as a development dependency:

npm install --save-dev nodemon # or using yarn: yarn add nodemon -D

With a local installation, nodemon will not be available in your system path or you can't use it directly from the command line. Instead, the local installation of nodemon can be run by calling it from within an npm script (such as npm start) or using npx nodemon.

Usage

nodemon wraps your application, so you can pass all the arguments you would normally pass to your app:

nodemon [your node app]

For CLI options, use the -h (or --help) argument:

nodemon -h

Using nodemon is simple, if my application accepted a host and port as the arguments, I would start it as so:

nodemon ./server.js localhost 8080

Any output from this script is prefixed with [nodemon], otherwise all output from your application, errors included, will be echoed out as expected.

You can also pass the inspect flag to node through the command line as you would normally:

nodemon --inspect ./server.js 80

If you have a package.json file for your app, you can omit the main script entirely and nodemon will read the package.json for the main property and use that value as the app (ref).

nodemon will also search for the scripts.start property in package.json (as of nodemon 1.1.x).

Also check out the FAQ or issues for nodemon.

Automatic re-running

nodemon was originally written to restart hanging processes such as web servers, but now supports apps that cleanly exit. If your script exits cleanly, nodemon will continue to monitor the directory (or directories) and restart the script if there are any changes.

Manual restarting

Whilst nodemon is running, if you need to manually restart your application, instead of stopping and restart nodemon, you can type rs with a carriage return, and nodemon will restart your process.

Config files

nodemon supports local and global configuration files. These are usually named nodemon.json and can be located in the current working directory or in your home directory. An alternative local configuration file can be specified with the --config <file> option.

The specificity is as follows, so that a command line argument will always override the config file settings:

  • command line arguments
  • local config
  • global config

A config file can take any of the command line arguments as JSON key values, for example:

{
  "verbose": true,
  "ignore": ["*.test.js", "**/fixtures/**"],
  "execMap": {
    "rb": "ruby",
    "pde": "processing --sketch={{pwd}} --run"
  }
}

The above nodemon.json file might be my global config so that I have support for ruby files and processing files, and I can run nodemon demo.pde and nodemon will automatically know how to run the script even though out of the box support for processing scripts.

A further example of options can be seen in sample-nodemon.md

package.json

If you want to keep all your package configurations in one place, nodemon supports using package.json for configuration. Specify the config in the same format as you would for a config file but under nodemonConfig in the package.json file, for example, take the following package.json:

{
  "name": "nodemon",
  "homepage": "http://nodemon.io",
  "...": "... other standard package.json values",
  "nodemonConfig": {
    "ignore": ["**/test/**", "**/docs/**"],
    "delay": 2500
  }
}

Note that if you specify a --config file or provide a local nodemon.json any package.json config is ignored.

This section needs better documentation, but for now you can also see nodemon --help config (also here).

Using nodemon as a module

Please see doc/requireable.md

Using nodemon as child process

Please see doc/events.md

Running non-node scripts

nodemon can also be used to execute and monitor other programs. nodemon will read the file extension of the script being run and monitor that extension instead of .js if there's no nodemon.json:

nodemon --exec "python -v" ./app.py

Now nodemon will run app.py with python in verbose mode (note that if you're not passing args to the exec program, you don't need the quotes), and look for new or modified files with the .py extension.

Default executables

Using the nodemon.json config file, you can define your own default executables using the execMap property. This is particularly useful if you're working with a language that isn't supported by default by nodemon.

To add support for nodemon to know about the .pl extension (for Perl), the nodemon.json file would add:

{
  "execMap": {
    "pl": "perl"
  }
}

Now running the following, nodemon will know to use perl as the executable:

nodemon script.pl

It's generally recommended to use the global nodemon.json to add your own execMap options. However, if there's a common default that's missing, this can be merged in to the project so that nodemon supports it by default, by changing default.js and sending a pull request.

Monitoring multiple directories

By default nodemon monitors the current working directory. If you want to take control of that option, use the --watch option to add specific paths:

nodemon --watch app --watch libs app/server.js

Now nodemon will only restart if there are changes in the ./app or ./libs directory. By default nodemon will traverse sub-directories, so there's no need in explicitly including sub-directories.

Nodemon also supports unix globbing, e.g --watch './lib/*'. The globbing pattern must be quoted. For advanced globbing, see picomatch documentation, the library that nodemon uses through chokidar (which in turn uses it through anymatch).

Specifying extension watch list

By default, nodemon looks for files with the .js, .mjs, .coffee, .litcoffee, and .json extensions. If you use the --exec option and monitor app.py nodemon will monitor files with the extension of .py. However, you can specify your own list with the -e (or --ext) switch like so:

nodemon -e js,pug

Now nodemon will restart on any changes to files in the directory (or subdirectories) with the extensions .js, .pug.

Ignoring files

By default, nodemon will only restart when a .js JavaScript file changes. In some cases you will want to ignore some specific files, directories or file patterns, to prevent nodemon from prematurely restarting your application.

This can be done via the command line:

nodemon --ignore lib/ --ignore tests/

Or specific files can be ignored:

nodemon --ignore lib/app.js

Patterns can also be ignored (but be sure to quote the arguments):

nodemon --ignore 'lib/*.js'

Important the ignore rules are patterns matched to the full absolute path, and this determines how many files are monitored. If using a wild card glob pattern, it needs to be used as ** or omitted entirely. For example, nodemon --ignore '**/test/**' will work, whereas --ignore '*/test/*' will not.

Note that by default, nodemon will ignore the .git, node_modules, bower_components, .nyc_output, coverage and .sass-cache directories and add your ignored patterns to the list. If you want to indeed watch a directory like node_modules, you need to override the underlying default ignore rules.

Application isn't restarting

In some networked environments (such as a container running nodemon reading across a mounted drive), you will need to use the legacyWatch: true which enables Chokidar's polling.

Via the CLI, use either --legacy-watch or -L for short:

nodemon -L

Though this should be a last resort as it will poll every file it can find.

Delaying restarting

In some situations, you may want to wait until a number of files have changed. The timeout before checking for new file changes is 1 second. If you're uploading a number of files and it's taking some number of seconds, this could cause your app to restart multiple times unnecessarily.

To add an extra throttle, or delay restarting, use the --delay command:

nodemon --delay 10 server.js

For more precision, milliseconds can be specified. Either as a float:

nodemon --delay 2.5 server.js

Or using the time specifier (ms):

nodemon --delay 2500ms server.js

The delay figure is number of seconds (or milliseconds, if specified) to delay before restarting. So nodemon will only restart your app the given number of seconds after the last file change.

If you are setting this value in nodemon.json, the value will always be interpreted in milliseconds. E.g., the following are equivalent:

nodemon --delay 2.5

{
  "delay": 2500
}

Gracefully reloading down your script

It is possible to have nodemon send any signal that you specify to your application.

nodemon --signal SIGHUP server.js

Your application can handle the signal as follows.

process.on("SIGHUP", function () {
  reloadSomeConfiguration();
  process.kill(process.pid, "SIGTERM");
})

Please note that nodemon will send this signal to every process in the process tree.

If you are using cluster, then each workers (as well as the master) will receive the signal. If you wish to terminate all workers on receiving a SIGHUP, a common pattern is to catch the SIGHUP in the master, and forward SIGTERM to all workers, while ensuring that all workers ignore SIGHUP.

if (cluster.isMaster) {
  process.on("SIGHUP", function () {
    for (const worker of Object.values(cluster.workers)) {
      worker.process.kill("SIGTERM");
    }
  });
} else {
  process.on("SIGHUP", function() {})
}

Controlling shutdown of your script

nodemon sends a kill signal to your application when it sees a file update. If you need to clean up on shutdown inside your script you can capture the kill signal and handle it yourself.

The following example will listen once for the SIGUSR2 signal (used by nodemon to restart), run the clean up process and then kill itself for nodemon to continue control:

// important to use `on` and not `once` as nodemon can re-send the kill signal
process.on('SIGUSR2', function () {
  gracefulShutdown(function () {
    process.kill(process.pid, 'SIGTERM');
  });
});

Note that the process.kill is only called once your shutdown jobs are complete. Hat tip to Benjie Gillam for writing this technique up.

Triggering events when nodemon state changes

If you want growl like notifications when nodemon restarts or to trigger an action when an event happens, then you can either require nodemon or add event actions to your nodemon.json file.

For example, to trigger a notification on a Mac when nodemon restarts, nodemon.json looks like this:

{
  "events": {
    "restart": "osascript -e 'display notification \"app restarted\" with title \"nodemon\"'"
  }
}

A full list of available events is listed on the event states wiki. Note that you can bind to both states and messages.

Pipe output to somewhere else

nodemon({
  script: ...,
  stdout: false // important: this tells nodemon not to output to console
}).on('readable', function() { // the `readable` event indicates that data is ready to pick up
  this.stdout.pipe(fs.createWriteStream('output.txt'));
  this.stderr.pipe(fs.createWriteStream('err.txt'));
});

Using nodemon in your gulp workflow

Check out the gulp-nodemon plugin to integrate nodemon with the rest of your project's gulp workflow.

Using nodemon in your Grunt workflow

Check out the grunt-nodemon plugin to integrate nodemon with the rest of your project's grunt workflow.

Pronunciation

nodemon, is it pronounced: node-mon, no-demon or node-e-mon (like pokémon)?

Well...I've been asked this many times before. I like that I've been asked this before. There's been bets as to which one it actually is.

The answer is simple, but possibly frustrating. I'm not saying (how I pronounce it). It's up to you to call it as you like. All answers are correct :)

Design principles

  • Fewer flags is better
  • Works across all platforms
  • Fewer features
  • Let individuals build on top of nodemon
  • Offer all CLI functionality as an API
  • Contributions must have and pass tests

Nodemon is not perfect, and CLI arguments has sprawled beyond where I'm completely happy, but perhaps it can be reduced a little one day.

FAQ

See the FAQ and please add your own questions if you think they would help others.

Backers

Thank you to all our backers! 🙏

nodemon backers

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. Sponsor this project today ❤️

Netpositive Best online casinos not on GamStop in the UK TheCasinoDB Goread.io Best Australian online casinos. Reviewed by Correct Casinos. Website dedicated to finding the best and safest licensed online casinos in India nongamstopcasinos.net Buy Instagram Likes OnlineCasinosSpelen Beoordelen van nieuwe online casino's 2023 CasinoZonderRegistratie.net - Nederlandse Top Casino's Famoid is a digital marketing agency that specializes in social media services and tools. ігрові автомати беткінг We are the leading Nearshore Technology Solutions company. We architect and engineer scalable and high-performing software solutions. Buy real Instagram followers from Twicsy starting at only $2.97. Twicsy has been voted the best site to buy followers from the likes of US Magazine. SocialWick offers the best Instagram Followers in the market. If you are looking to boost your organic growth, buy Instagram followers from SocialWick Online United States Casinos Looking to boost your YouTube channel? Buy YouTube subscribers with Views4You and watch your audience grow! Buy Telegram Members We review the entire iGaming industry from A to Z UpGrow is the Best Instagram Growth Service in 2024. Get more real Instagram followers with our AI-powered growth engine to get 10x faster results. CryptoCasinos.online No deposit casino promo Codes 2024 - The best online Casinos websites. No deposit bonus codes, Free Spins and Promo Codes. Stake, Roobet, Jackpotcity and more. Online casino. Find the social proof you need to reach your audience! Boost conversions. Quickly buy Twitter Followers & more with no sign-up. Taking you to the next Boost your social media presence effortlessly with top-quality Instagram and TikTok followers and likes. Social Media Management and all kinds of followers Betwinner is an online bookmaker offering sports betting, casino games, and more. At Buzzoid, you can buy Instagram followers quickly, safely, and easily with just a few clicks. Rated world's #1 IG service since 2012. Zamsino.com Reviewing and comparing online casinos available to Finnish players. In addition, we publish relevant news and blog posts about the world of iGaming. Онлайн казино та БК (ставки на спорт) в Україні Prank Caller - #1 Prank Calling App Buzzvoice is your one-stop shop for all your social media marketing needs. With Buzzvoice, you can buy followers, comments, likes, video views and more! At Famety, you can grow your social media following quickly, safely, and easily with just a few clicks. Rated the world’s #1 social media service since 2013. Buy Twitter Followers Visit TweSocial SocialBoosting: Buy Instagram & TikTok Followers, Likes, Views Buy Youtube Subscribers from the #1 rated company. Our exclusive high quality Youtube subscribers come with a lifetime guarantee! Ігрові автомати онлайн Kasinohai.com Casino Online Chile At Buzzoid, you can buy YouTube views easily and safely. Webisoft casinos sin licencia en España casino online chile online casino australia JokaCasino Vanguard Media évalue les casinos en ligne pour joueurs français, testant les sites en France. Nos classements stricts garantissent des casinos fiables et sûrs. kasyno online polska FAVBET Bei Releaf erhalten Sie schnell und diskret Ihr Cannabis Rezept online. Unsere Ärzte prüfen Ihre Angaben und stellen bei Eignung das Rezept aus. Anschließend können Sie legal und sicher medizinisches Cannabis über unsere Partnerapotheken kaufen. Kasyno Online Analysis of online casinos with the best payouts Нова українська букмекерська контора Buy TikTok Custom Comments

Please note that links to the sponsors above are not direct endorsements nor affiliated with any of contributors of the nodemon project.

License

MIT http://rem.mit-license.org