chokidar-cli、grunt-contrib-watch、gulp-watch、nodemon、onchange 和 watch 都是用于监听文件系统变化并触发相应操作的 Node.js 工具,广泛应用于开发流程自动化(如热重载、构建、测试等)。它们基于底层文件监听库(如 chokidar 或 fs.watch),但面向不同使用场景和构建体系:nodemon 专为重启 Node.js 应用设计;grunt-contrib-watch 和 gulp-watch 分别集成于 Grunt 和 Gulp 构建生态;而 chokidar-cli、onchange 和 watch 则提供更通用的命令行接口,适用于任意 shell 命令的触发。这些工具在配置方式、性能表现、跨平台兼容性及与现代工具链的集成能力上存在显著差异。
在前端工程化中,监听文件变化并自动触发构建、测试或重启是提升开发效率的核心环节。虽然这些工具表面功能相似,但它们的设计目标、适用场景和技术实现差异巨大。本文从真实开发痛点出发,深入比较六款主流监听工具的技术细节,帮助你做出精准选型。
首先明确:这些工具并非彼此替代关系,而是服务于不同技术栈和工作流。
nodemon 是 Node.js 进程管理器,专为重启服务设计。grunt-contrib-watch 和 gulp-watch 是 构建系统插件,分别绑定 Grunt 和 Gulp。chokidar-cli、onchange 和 watch 是 通用命令行监听器,可触发任意 shell 命令。💡 关键洞察:如果你的项目不使用 Grunt/Gulp,就不要为了监听文件而引入整个构建系统。
底层监听机制直接影响稳定性和性能。
chokidar-cli、gulp-watch(v5+)和 onchange 均基于 chokidar —— 它封装了 fs.watch、fsevents(macOS)和轮询机制,在所有平台提供一致行为,能正确处理符号链接、大目录和网络驱动器。watch 直接使用 Node.js 原生 fs.watch,在 macOS 和 Windows 上存在已知问题(如子目录监听失效、事件重复触发)。nodemon 内部使用 chokidar(自 v2.0 起),确保高可靠性。grunt-contrib-watch 默认使用 gaze(已归档),虽可切换至 chokidar,但配置复杂且社区支持弱。# 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-cli | onchange | watch | nodemon | gulp-watch | grunt-contrib-watch |
|---|---|---|---|---|---|---|
| 防抖/延迟 | ✅ -d, --debounce | ❌ | ❌ | ✅ --delay | ✅ .pipe(wait()) | ✅ options: { debounceDelay } |
| 仅监听 add 事件 | ✅ -a, --add | ❌ | ❌ | ❌ | ✅ { events: ['add'] } | ❌ |
| 忽略 node_modules | ✅ 默认忽略 | ✅ 默认忽略 | ❌ 需手动排除 | ✅ 默认忽略 | ✅ 可配置 | ✅ 可配置 |
| 传递文件路径 | ✅ {path} 占位符 | ✅ {changed} | ❌ | ❌ | ✅ Vinyl 对象 | ❌ |
# 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-cli、onchange)适合补充现代工具链的盲区,例如:
# 监听 content 目录生成静态站点
npx onchange 'content/**/*' -- eleventy
Grunt/Gulp 插件 在新项目中已无必要。现代 bundler(如 Webpack 的 watchOptions、Vite 的 HMR)内置高效监听,无需额外插件。
grunt-contrib-watch:Grunt 生态已停滞,该插件最后一次主要更新在 2018 年。新项目绝对不要使用。watch:虽仍可安装,但长期未更新,且依赖不可靠的 fs.watch。仅限临时脚本。chokidar-cli、gulp-watch、nodemon、onchange)均活跃维护,兼容 Node.js LTS 版本。根据你的具体场景快速判断:
nodemongulp-watchgrunt-contrib-watch(但计划迁移)chokidar-cli(功能全)或 onchange(语法简)watch,但别用于正式项目chokidar-cli 是通用场景的首选,尤其当你需要事件过滤或延迟执行。onchange 的语法更接近自然语言,适合快速编写 npm scripts。nodemon 提供开箱即用的智能重启,无可替代。watch 或 grunt-contrib-watch。最终,工具的价值在于解决实际问题。理解每个工具的设计边界,才能避免“用大炮打蚊子”或“用螺丝刀砍树”的工程陷阱。
选择 nodemon 如果你开发的是 Node.js 后端服务或 CLI 工具,需要在代码变更时自动重启进程。它内置智能忽略规则(如 node_modules)、支持配置文件和信号控制,是 Node.js 开发的事实标准。但它不适合前端资源构建或通用文件监听场景。
选择 watch 如果你需要最简化的监听逻辑且对性能要求不高。它基于原生 fs.watch,API 极简(watch 'command' 'dir'),但跨平台稳定性较差(尤其在 macOS 和 Windows 上可能出现重复事件或漏报)。仅建议用于简单脚本或临时调试,生产级项目应优先考虑基于 chokidar 的方案。
选择 chokidar-cli 如果你需要一个轻量、灵活且基于 chokidar 的命令行监听器,支持 glob 模式、延迟执行和精确的事件过滤(如仅 on-add)。它不绑定特定构建系统,适合在 npm scripts 中直接调用任意命令,尤其适用于需要精细控制监听行为的现代前端项目。
选择 grunt-contrib-watch 仅当你仍在维护基于 Grunt 的旧项目。该插件深度集成 Grunt 任务系统,支持 livereload 和任务依赖,但 Grunt 生态已基本被 Webpack、Vite 等现代工具取代。新项目应避免引入 Grunt 及其相关插件。
选择 onchange 如果你偏好简洁的命令行语法、支持通配符路径和跨平台 shell 命令执行。它的 API 直观(类似 onchange 'src/**/*' -- npm run build),启动快,适合集成到 npm scripts 中。但功能相对基础,缺乏高级过滤或延迟控制选项。
选择 gulp-watch 如果你的构建流程完全基于 Gulp 且需要流式(stream-based)文件处理。它返回 Vinyl 文件对象流,可无缝接入 Gulp 管道,但若项目未使用 Gulp,则引入它会带来不必要的复杂性。对于非 Gulp 项目,更简单的 CLI 工具是更好选择。
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.
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.
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.
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.
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.
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:
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
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).
Please see doc/requireable.md
Please see doc/events.md
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.
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.
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).
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.
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.
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.
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
}
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() {})
}
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.
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.
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'));
});
Check out the gulp-nodemon plugin to integrate nodemon with the rest of your project's gulp workflow.
Check out the grunt-nodemon plugin to integrate nodemon with the rest of your project's grunt workflow.
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 :)
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.
See the FAQ and please add your own questions if you think they would help others.
Thank you to all our backers! 🙏
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. Sponsor this project today ❤️
Please note that links to the sponsors above are not direct endorsements nor affiliated with any of contributors of the nodemon project.