chokidar-cli、grunt-contrib-watch、gulp-watch 和 nodemon 都是用于监控文件变化并触发相应动作的开发工具,但它们的应用场景和底层机制有所不同。nodemon 专为 Node.js 服务器设计,用于检测代码变更并自动重启进程;chokidar-cli 是一个通用的命令行文件监听工具,适合执行任意 shell 命令;grunt-contrib-watch 和 gulp-watch 则是分别集成在 Grunt 和 Gulp 任务运行器中的插件,用于在传统构建流程中触发任务。选择哪个工具取决于你的项目架构是需要重启服务、运行构建任务,还是执行简单的脚本命令。
在现代化前端和 Node.js 开发中,文件监听是自动化工作流的核心环节。无论是编译 CSS、打包资源,还是重启服务器,都需要工具来检测文件变化并触发动作。chokidar-cli、grunt-contrib-watch、gulp-watch 和 nodemon 是四个常见的选择,但它们的定位完全不同。本文将从核心用途、配置方式、生态集成和维护状态四个方面进行深度对比,帮助你在架构选型时做出正确决定。
这四个工具最大的区别在于它们对“文件变化”的反应方式。
nodemon 专注于 Node.js 进程管理。
// nodemon: 配置文件 nodemon.json
{
"watch": ["src"],
"ext": "js,json",
"exec": "node ./src/index.js"
}
chokidar-cli 专注于 通用文件监听。
package.json 中快速添加监听逻辑。# chokidar-cli: 命令行用法
npx chokidar "**/*.css" -c "npm run build:css"
grunt-contrib-watch 专注于 Grunt 任务触发。
// grunt-contrib-watch: Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
watch: {
scripts: {
files: ['**/*.js'],
tasks: ['uglify']
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
};
gulp-watch 专注于 Gulp 流式处理。
// gulp-watch: gulpfile.js
const gulp = require('gulp');
const watch = require('gulp-watch');
watch('**/*.scss', function() {
return gulp.src('**/*.scss')
.pipe(gulp.dest('dist/css'));
});
配置文件的格式直接影响开发体验和维护成本。
nodemon 支持 JSON 配置或命令行参数。
nodemon.json 可以固化配置,方便团队共享。--exec 等参数。# nodemon: 命令行直接启动
nodemon --watch src --ext js --exec "node src/app.js"
chokidar-cli 主要通过命令行参数配置。
// package.json 脚本示例
{
"scripts": {
"watch:css": "chokidar 'src/**/*.css' -c 'postcss src/**/*.css'"
}
}
grunt-contrib-watch 必须使用 JavaScript 配置对象。
Gruntfile.js 中,结构较为繁琐。files 数组和 tasks 数组。// grunt-contrib-watch: 多目标配置
watch: {
css: {
files: ['src/**/*.css'],
tasks: ['cssmin']
},
js: {
files: ['src/**/*.js'],
tasks: ['uglify']
}
}
gulp-watch 使用 JavaScript 函数定义逻辑。
// gulp-watch: 自定义回调
watch('src/**/*.js', function(vinylFile) {
console.log('File changed: ' + vinylFile.path);
// 可以针对单个文件做特定处理
});
工具是否依赖特定的任务运行器,决定了它在项目中的耦合度。
nodemon 是 独立工具。
# 独立运行,不依赖构建工具
nodemon server.js
chokidar-cli 是 独立命令行工具。
chokidar 库,但不需要编写 JS 代码。# 配合其他命令使用
chokidar "templates/**" -c "npm run render"
grunt-contrib-watch 强依赖 Grunt 生态。
grunt 和 grunt-cli。// 必须加载 grunt 任务
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['watch']);
gulp-watch 强依赖 Gulp 生态。
// 必须引入 gulp 核心
const gulp = require('gulp');
// 插件依附于 gulp 实例
gulp.watch(...);
工具的活跃度和社区支持直接影响长期维护成本。
nodemon 处于 活跃维护 状态。
// 推荐用于后端服务
{
"scripts": {
"dev": "nodemon src/index.js"
}
}
chokidar-cli 处于 稳定但低频更新 状态。
chokidar 库非常活跃(被 Vite、Webpack 使用)。chokidar JS 库。// 复杂场景建议直接用 JS 库
const chokidar = require('chokidar');
chokidar.watch('.').on('change', path => console.log(path));
grunt-contrib-watch 处于 遗留维护 状态。
// 遗留项目示例,新项目应避免
// 不推荐:grunt.initConfig({...})
gulp-watch 处于 稳定维护 状态。
// 适合 Gulp 工作流
// 推荐:仅在已有 Gulp 架构中使用
| 特性 | nodemon | chokidar-cli | grunt-contrib-watch | gulp-watch |
|---|---|---|---|---|
| 核心功能 | 重启 Node 进程 | 执行 Shell 命令 | 触发 Grunt 任务 | 触发 Gulp 任务 |
| 配置方式 | JSON 或 CLI | 命令行参数 | JS 配置对象 | JS 函数回调 |
| 依赖环境 | 独立 | 独立 | 必须 Grunt | 必须 Gulp |
| 适用场景 | 后端开发 | 简单脚本监听 | 遗留 Grunt 项目 | Gulp 构建流 |
| 新项目推荐 | ✅ 后端首选 | ⚠️ 简单场景 | ❌ 不推荐 | ⚠️ 特定场景 |
nodemon 是后端开发的必备工具 🛠️ — 如果你的项目包含 Node.js 服务器,直接使用它来管理进程重启,不要尝试用其他监听工具替代这个功能。
chokidar-cli 适合轻量级自动化 🪶 — 如果你只需要在文件变动时跑一条命令,且不想引入沉重的任务运行器,它是 npm scripts 的最佳搭档。
gulp-watch 适合特定构建流 🔄 — 如果你的团队已经深度使用 Gulp 处理静态资源或复杂管道,继续使用它可以保持一致性,但不要为了监听而引入 Gulp。
grunt-contrib-watch 仅用于维护旧项目 🕰️ — 对于新架构,请避免使用 Grunt。现代打包工具(如 Vite、Webpack)已内置高效监听,无需额外插件。
最终建议:现代前端项目通常不需要独立的文件监听工具,因为打包工具已内置该功能。后端服务请用 nodemon。只有在需要自定义脚本联动且无法通过打包工具实现时,才考虑 chokidar-cli。避免为了监听而引入过时的任务运行器。
选择 nodemon 如果你正在开发 Node.js 后端服务,需要在代码修改后自动重启服务器。它是后端开发的标准工具,不支持前端构建任务,专注于进程管理而非文件编译。
选择 chokidar-cli 如果你需要在 npm scripts 中快速添加文件监听逻辑,而不想引入完整的任务运行器。它适合简单的场景,比如文件变动时运行一条 shell 命令,配置简单且依赖轻量。
选择 grunt-contrib-watch 仅当你正在维护基于 Grunt 的遗留项目。对于新项目不建议使用,因为 Grunt 生态系统已逐渐被更现代的工具取代,维护成本较高且配置繁琐。
选择 gulp-watch 如果你的构建流程已经基于 Gulp,并且需要细粒度的文件流控制。它在 Gulp 生态中表现良好,适合处理复杂的管道任务,但前提是团队已熟悉 Gulp 体系。
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.