@a1motion/nodemon 中文文档教程
nodemon
nodemon 是一种工具,通过在检测到目录中的文件更改时自动重启节点应用程序来帮助开发基于 node.js 的应用程序。
nodemon 不需要对您的代码或开发方法进行任何额外更改。 nodemon 是 node
的替代包装器,在执行脚本时使用 nodemon
替换命令行上的单词 node
。
Installation
通过使用 git 克隆或使用npm(推荐方式):
npm install -g nodemon
nodemon 将全局安装到您的系统路径。
您还可以将 nodemon 安装为开发依赖项:
npm install --save-dev nodemon
使用本地安装,nodemon 将不会出现在您的系统路径中。 相反,可以通过从 npm 脚本(例如 npm start
)或使用 npx nodemon
调用它来运行 nodemon 的本地安装。
Usage
nodemon 包装您的应用程序,因此您可以将通常传递给您的应用程序的所有参数传递给您的应用程序:
nodemon [your node app]
对于 CLI 选项,使用 -h
(或 --help
)参数:
nodemon -h
使用 nodemon 很简单,如果我的应用程序接受主机和端口作为参数,我会这样启动它:
nodemon ./server.js localhost 8080
此脚本的任何输出都以 [nodemon]
为前缀,否则所有应用程序的输出,包含的错误将按预期回显。
如果没有给出脚本,nodemon 将测试 package.json
文件,如果找到,将运行与 main 属性关联的文件 (ref)。
您还可以像往常一样通过命令行将 inspect
标志传递给节点:
nodemon --inspect ./server.js 80
如果您的应用程序有一个 package.json
文件,则可以省略主脚本完全和 nodemon 将读取 package.json
的 main
属性并将该值用作应用程序。
nodemon 还将在 package.json
中搜索 scripts.start
属性(从 nodemon 1.1.x 开始)。
另请查看FAQ 或 关于 nodemon 的问题。
Automatic re-running
nodemon 最初是为重新启动挂起的进程(例如 Web 服务器)而编写的,但现在支持干净退出的应用程序。 如果您的脚本干净地退出,nodemon 将继续监视目录(或多个目录)并在有任何更改时重新启动脚本。
Manual restarting
当 nodemon 正在运行时,如果您需要手动重新启动您的应用程序,而不是停止并重新启动 nodemon,您可以键入 rs
并回车,nodemon 将重新启动您的进程。
Config files
nodemon 支持本地和全局配置文件。 这些通常被命名为 nodemon.json
并且可以位于当前工作目录或您的主目录中。 可以使用 --config
选项指定替代的本地配置文件。
具体如下,因此命令行参数将始终覆盖配置文件设置:
- command line arguments
- local config
- global config
配置文件可以将任何命令行参数作为 JSON 键值,例如:
{
"verbose": true,
"ignore": ["*.test.js", "fixtures/*"],
"execMap": {
"rb": "ruby",
"pde": "processing --sketch={{pwd}} --run"
}
}
上面的 nodemon.json
文件可能是我的全局配置,因此我支持 ruby 文件和处理文件,我可以运行 nodemon demo.pde
并且 nodemon 会自动知道如何运行脚本,即使开箱即用支持处理脚本。
选项的进一步示例可以在 sample-nodemon.md 中看到
package.json
如果你想要将所有包配置放在一个地方,nodemon 支持使用 package.json
进行配置。 以与配置文件相同的格式指定配置,但在 package.json
文件中的 nodemonConfig
下,例如,采用以下 package.json
:
{
"name": "nodemon",
"homepage": "http://nodemon.io",
"...": "... other standard package.json values",
"nodemonConfig": {
"ignore": ["test/*", "docs/*"],
"delay": "2500"
}
}
请注意,如果您指定 --config
文件或提供本地 nodemon.json
任何 package.json
配置将被忽略.
这部分需要更好的文档,但现在您还可以查看 nodemon --help config
(也在这里)。
Using nodemon as a module
Using nodemon as child process
Running non-node scripts
nodemon可以也可用于执行和监控其他程序。 如果没有 nodemon.json
,nodemon 将读取正在运行的脚本的文件扩展名并监视该扩展名而不是 .js
:
nodemon --exec "python -v" ./app.py
现在 nodemon 将运行 app.py
在详细模式下使用 python(请注意,如果您没有将 args 传递给 exec 程序,则不需要引号),并使用 .py
扩展。
Default executables
使用 nodemon.json
配置文件,您可以使用 execMap
属性定义您自己的默认可执行文件。 如果您正在使用 nodemon 默认不支持的语言,这将特别有用。
要添加对 nodemon 的支持以了解 .pl
扩展名(对于 Perl),nodemon.json
文件将添加:
{
"execMap": {
"pl": "perl"
}
}
现在运行以下命令,nodemon 将知道使用 < code>perl 作为可执行文件:
nodemon script.pl
通常建议使用全局 nodemon.json
添加您自己的 execMap
选项。 但是,如果缺少一个通用默认值,可以将其合并到项目中,以便 nodemon 默认支持它,方法是更改 default.js 并发送拉取请求。
Monitoring multiple directories
默认情况下,nodemon 监视当前工作目录。 如果您想控制该选项,请使用 --watch
选项添加特定路径:
nodemon --watch app --watch libs app/server.js
现在 nodemon 只会在 ./app
或./libs
目录。 默认情况下,nodemon 将遍历子目录,因此无需显式包含子目录。
不要使用 unix globbing 传递多个目录,例如 --watch ./lib/*
,它不会工作。 每个目录都需要一个 --watch
标记。
Specifying extension watch list
默认情况下,nodemon 查找具有 .js
、.mjs
、.coffee
、.litcoffee
和.json
扩展名。 如果您使用--exec
选项并监控app.py
,nodemon 将监控扩展名为.py
的文件。 但是,您可以使用 -e
(或 --ext
)开关指定您自己的列表,如下所示:
nodemon -e js,jade
现在 nodemon 将在目录(或子目录),扩展名为 .js
、.jade
。
Ignoring files
默认情况下,nodemon 只会在 .js
JavaScript 文件更改时重新启动。 在某些情况下,您会想要忽略一些特定的文件、目录或文件模式,以防止 nodemon 过早地重新启动您的应用程序。
这可以通过命令行完成:
nodemon --ignore lib/ --ignore tests/
或者可以忽略特定文件:
nodemon --ignore lib/app.js
也可以忽略模式(但一定要引用参数):
nodemon --ignore 'lib/*.js'
注意默认情况下,nodemon 将忽略 .git
, node_modules
、bower_components
、.nyc_output
、coverage
和 .sass-cache
目录和将您忽略的模式添加到列表中。 如果你确实想查看像 node_modules
这样的目录,你需要 覆盖底层默认忽略规则。
Application isn't restarting
在某些网络环境中(例如运行 nodemon 的容器读取已安装的驱动器),您将需要使用启用 Chokidar 轮询的 legacyWatch: true
。
通过 CLI,使用 --legacy-watch
或 -L
简称:
nodemon -L
虽然这应该是最后的手段,因为它会轮询它可以找到的每个文件。
Delaying restarting
在某些情况下,您可能希望等到一些文件发生更改。 检查新文件更改之前的超时时间为 1 秒。 如果您要上传大量文件并且需要几秒钟的时间,这可能会导致您的应用不必要地重启多次。
要添加额外的限制或延迟重新启动,请使用 --delay
命令:
nodemon --delay 10 server.js
为了更精确,可以指定毫秒。 作为浮点数:
nodemon --delay 2.5 server.js
或使用时间说明符 (ms):
nodemon --delay 2500ms server.js
延迟数字是重新启动前延迟的秒数(或毫秒,如果指定)。 因此,nodemon 只会在最后 文件更改后的给定秒数后重新启动您的应用程序。
如果您在 nodemon.json
中设置此值,则该值将始终以毫秒为单位进行解释。 例如,以下是等价的:
nodemon --delay 2.5
{
"delay": "2500"
}
Gracefully reloading down your script
可以让 nodemon 发送您指定的任何信号给您的应用程序。
nodemon --signal SIGHUP server.js
您的应用程序可以按如下方式处理信号。
process.once("SIGHUP", function () {
reloadSomeConfiguration();
})
请注意,nodemon 会将此信号发送到进程树中的每个进程。
如果您使用的是 cluster
,那么每个 worker(以及 master)都会收到信号。 如果您希望在收到 SIGHUP
时终止所有 worker,常见的模式是在 master 中捕获 SIGHUP
,并将 SIGTERM
转发给所有工人,同时确保所有工人都忽略 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 看到文件更新时,它会向您的应用程序发送一个 kill 信号。 如果您需要在脚本中关闭时进行清理,您可以捕获终止信号并自行处理。
下面的示例将监听一次 SIGUSR2
信号(由 nodemon 用于重新启动),运行清理进程,然后 kill 自身以便 nodemon 继续控制:
process.once('SIGUSR2', function () {
gracefulShutdown(function () {
process.kill(process.pid, 'SIGUSR2');
});
});
请注意 process.kill< /code> 仅在您的关闭作业完成后调用。 向 Benjie Gillam 的写作致敬这个技术了。
Triggering events when nodemon state changes
如果您想在 nodemon 重新启动时发出类似通知的咆哮或在事件发生时触发操作,那么您可以 require
nodemon 或将事件操作添加到您的 nodemon.json
文件。
例如,要在 Nodemon 重新启动时在 Mac 上触发通知,nodemon.json
如下所示:
{
"events": {
"restart": "osascript -e 'display notification \"app restarted\" with title \"nodemon\"'"
}
}
事件状态 wiki。 请注意,您可以绑定状态和消息。
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
查看 gulp-nodemon 插件,将 nodemon 与项目的其余 gulp 工作流集成。
Using nodemon in your Grunt workflow
查看 grunt-nodemon 插件,将 nodemon 与项目的其他 grunt 工作流集成。
Pronunciation
nodemon,它的发音是:node-mon、no-demon 还是 node-e-mon(如神奇宝贝)?
嗯……我以前被问过很多次了。 我喜欢我以前被问过这个问题。 有人打赌它到底是哪一个。
答案很简单,但可能令人沮丧。 我不是在说(我怎么发音)。 随心所欲地称呼它。 所有答案都是正确的 :)
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 并不完美,CLI 争论已经超出了我完全满意的范围,但也许有一天它可以减少一点。
FAQ
请参阅常见问题解答,如果您认为这些问题会对他人有所帮助,请添加您自己的问题。
Backers
感谢所有我们的支持者! ???
Sponsors
成为赞助商来支持这个项目。 您的徽标将显示在此处,并带有指向您网站的链接。 今天赞助这个项目❤️
License
麻省理工学院 http://rem.mit-license.org
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.
Installation
Either through cloning with git or by using npm (the recommended way):
npm install -g 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
With a local installation, nodemon will not be available in your system path. 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.
If no script is given, nodemon will test for a package.json
file and if found, will run the file associated with the main property (ref).
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.
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.
Don't use unix globbing to pass multiple directories, e.g --watch ./lib/*
, it won't work. You need a --watch
flag per directory watched.
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,jade
Now nodemon will restart on any changes to files in the directory (or subdirectories) with the extensions .js
, .jade
.
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'
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.once("SIGHUP", function () {
reloadSomeConfiguration();
})
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:
process.once('SIGUSR2', function () {
gracefulShutdown(function () {
process.kill(process.pid, 'SIGUSR2');
});
});
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! ????
Sponsors
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. Sponsor this project today ❤️