npm系列:nodemon----一个自动重启 Node.js 应用程序的工具

 nodemon - npm (npmjs.com)icon-default.png?t=O83Ahttps://www.npmjs.com/package/nodemon

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.

nodemon

nodemon 是一个工具,它能够帮助开发者在检测到目录中的文件发生变化时,自动重启 Node.js 应用程序,从而辅助 Node.js 应用程序的开发。

nodemon 不需要您对代码或开发方法做任何额外的更改。nodemon 是 node 的一个替代包装器(wrapper)。要使用 nodemon,只需在执行脚本时,将命令行中的 node 一词替换为 nodemon 即可。

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.

安装

您可以通过使用 git 克隆,或者(推荐的方式)使用 npm 来安装 nodemon:

npm install -g nodemon # 或者使用 yarn: yarn global add nodemon

这样,nodemon 就会被全局安装到您的系统路径中。

您还可以将 nodemon 安装为开发依赖项:

npm install --save-dev nodemon # 或者使用 yarn: yarn add nodemon -D

如果进行本地安装,nodemon 将不会添加到您的系统路径中,您也无法直接从命令行使用它。相反,您可以通过在 npm 脚本(如 npm start)中调用它,或者使用 npx nodemon 来运行本地安装的 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.

使用

nodemon 包装了您的应用程序,因此您可以传递通常传递给应用程序的所有参数:

nodemon [您的 Node.js 应用]

要查看命令行选项,请使用 -h(或 --help)参数:

nodemon -h

使用 nodemon 非常简单,如果我的应用程序接受主机和端口作为参数,我会这样启动它:

nodemon ./server.js localhost 8080

该脚本的任何输出都会以 [nodemon] 为前缀,否则,您的应用程序的所有输出(包括错误)都会按预期回显出来。

您还可以通过命令行像平常一样将 inspect 标志传递给 node:

nodemon --inspect ./server.js 80

如果您的应用程序有一个 package.json 文件,您可以完全省略主脚本,nodemon 会读取 package.json 中的 main 属性,并使用该值作为应用程序(参考)。

从 nodemon 1.1.x 版本开始,nodemon 还会在 package.json 中搜索 scripts.start 属性。

此外,还可以查看 nodemon 的常见问题解答 (FAQ) 或问题跟踪。

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).

自动重新运行

nodemon 最初是为了重启挂起的进程(如 Web 服务器)而编写的,但现在它也支持干净退出的应用程序。如果您的脚本干净退出,nodemon 将继续监视目录(或多个目录),并在有任何更改时重新启动脚本。

手动重启

在 nodemon 运行期间,如果您需要手动重启应用程序,而不是停止并重新启动 nodemon,您可以输入 rs 并按下回车键,nodemon 将重启您的进程。

配置文件

nodemon 支持本地和全局配置文件。这些文件通常命名为 nodemon.json,可以位于当前工作目录或您的主目录中。可以使用 --config <file> 选项指定备用本地配置文件。

配置文件的优先级如下,因此命令行参数将始终覆盖配置文件设置:

  1. 命令行参数
  2. 本地配置
  3. 全局配置

配置文件可以包含任何命令行参数作为 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", 
"...": "... 其他标准的 package.json 值", 
"nodemonConfig": { 
"ignore": ["**/test/**", "**/docs/**"], 
"delay": 2500 
} 
}

请注意,如果您指定了 --config 文件或提供了本地 nodemon.json,则会忽略任何 package.json 配置。

这一节需要更好的文档,但目前您还可以查看 nodemon --help config(也在这里)。

使用 nodemon 作为模块

英文:
Using nodemon as a module
Please see doc/requireable.md

中文:
将 nodemon 用作模块
请参阅 doc/requireable.md


使用 nodemon 作为子进程

英文:
Using nodemon as child process
Please see doc/events.md

中文:
将 nodemon 用作子进程
请参阅 doc/events.md


运行非 Node.js 脚本

英文:
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.

中文:
运行非 Node.js 脚本
nodemon 还可以用于执行和监视其他程序。如果没有 nodemon.json 文件,nodemon 会读取正在运行的脚本的文件扩展名,并监视该扩展名而不是 .js:

nodemon --exec "python -v" ./app.py
现在,nodemon 将以详细模式使用 python 运行 app.py(注意,如果您没有向 exec 程序传递参数,则不需要引号),并查找具有 .py 扩展名的新文件或已修改文件。


默认可执行文件

英文:
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.

中文:
默认可执行文件
使用 nodemon.json 配置文件,您可以使用 execMap 属性定义自己的默认可执行文件。如果您正在使用的语言默认不受 nodemon 支持,这特别有用。

要为 nodemon 添加对 .pl 扩展名(用于 Perl)的支持,nodemon.json 文件将添加:

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

现在运行以下命令,nodemon 将知道要使用 perl 作为可执行文件:

nodemon script.pl

通常建议使用全局 nodemon.json 来添加自己的 execMap 选项。但是,如果缺少一个常见的默认设置,可以通过更改 default.js 并发送拉取请求来将其合并到项目中,以便 nodemon 默认支持它。

监控多个目录

英文:
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 监控当前工作目录。如果您想控制该选项,请使用 --watch 选项来添加特定路径:

nodemon --watch app --watch libs app/server.js
现在,只有当 ./app 或 ./libs 目录中的文件发生变化时,nodemon 才会重新启动。默认情况下,nodemon 会遍历子目录,因此无需显式包含子目录。


指定扩展名监控列表

英文:
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.

中文:
指定扩展名监控列表
默认情况下,nodemon 会查找具有 .js、.mjs、.coffee、.litcoffee 和 .json 扩展名的文件。如果您使用 --exec 选项并监控 app.py,nodemon 将监控具有 .py 扩展名的文件。但是,您可以使用 -e(或 --ext)选项来指定自己的列表,如下所示:

nodemon -e js,pug
现在,当目录(或子目录)中具有 .js、.pug 扩展名的文件发生任何更改时,nodemon 将重新启动。


忽略文件

英文:
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.

中文:
忽略文件
默认情况下,nodemon 仅在 .js JavaScript 文件更改时重新启动。在某些情况下,您可能希望忽略某些特定的文件、目录或文件模式,以防止 nodemon 过早地重新启动您的应用程序。

这可以通过命令行完成:

nodemon --ignore lib/ --ignore tests/
或者可以忽略特定文件:

nodemon --ignore lib/app.js
也可以忽略模式(但一定要为参数加引号):

nodemon --ignore 'lib/.js'
重要的是,忽略规则是与完整绝对路径匹配的模式,这决定了要监控的文件数量。如果使用通配符全局模式,则需要使用 ** 或完全省略。例如,nodemon --ignore '/test/' 将有效,而 --ignore '
/test/*' 将无效。

请注意,默认情况下,nodemon 将忽略 .git、node_modules、bower_components、.nyc_output、coverage 和 .sass-cache 目录,并将您忽略的模式添加到列表中。如果您确实想要监控像 node_modules 这样的目录,则需要覆盖底层的默认忽略规则。


应用程序未重启

英文:
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.

中文:
应用程序未重启
在某些网络环境中(例如,在容器中运行 nodemon 读取挂载的驱动器),您需要使用 legacyWatch: true,这将启用 Chokidar 的轮询功能。

通过命令行界面,可以使用 --legacy-watch 或简写 -L:

nodemon -L
尽管这应该是最后的手段,因为它会轮询找到的所有文件。


延迟重启

英文:
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
}

中文:
延迟重启
在某些情况下,您可能希望等到一定数量的文件发生更改后再进行重启。在检查新文件更改之前的超时时间为 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
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 可以向您的应用程序发送您指定的任何信号。

nodemon --signal SIGHUP server.js
您的应用程序可以按如下方式处理该信号。

process.on("SIGHUP", function () {
reloadSomeConfiguration();
process.kill(process.pid, "SIGTERM");
})
请注意,nodemon 会将此信号发送到进程树中的每个进程。

如果您正在使用 cluster,那么每个工作进程(以及主进程)都会收到该信号。如果您希望在收到 SIGHUP 时终止所有工作进程,一种常见的模式是在主进程中捕获 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 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.

中文:


控制脚本的关闭


当nodemon检测到文件更新时,它会向你的应用程序发送一个终止信号。如果你需要在脚本关闭时进行清理,你可以捕获这个终止信号并自行处理。

 
英文:
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.

中文:
以下示例将监听一次SIGUSR2信号(nodemon用于重启),运行清理过程,然后自行终止,以便nodemon继续控制:

// 重要的是使用on而不是once,因为nodemon可能会重新发送终止信号
process.on('SIGUSR2', function () {
gracefulShutdown(function () {
process.kill(process.pid, 'SIGTERM');
});
});
请注意,只有在你的关闭任务完成后才会调用process.kill。感谢Benjie Gillam撰写了这一技术。

 
英文:
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.

中文:


在nodemon状态改变时触发事件


如果你希望在nodemon重启时收到类似growl的通知,或者在事件发生时触发某个动作,那么你可以引入nodemon,或者在nodemon.json文件中添加事件动作。

 
英文:
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.

中文:
例如,要在Mac上触发nodemon重启时的通知,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'));
});

中文:


将输出传输到其他地方


nodemon({
script: ...,
stdout: false // 重要:这告诉nodemon不要将输出到控制台
}).on('readable', function() { // readable事件表示数据已准备好被读取
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.

中文:


在gulp工作流中使用nodemon


查看gulp-nodemon插件,将nodemon集成到你的项目的gulp工作流中。

英文:
Using nodemon in your Grunt workflow
Check out the grunt-nodemon plugin to integrate nodemon with the rest of your project's grunt workflow.

中文:


在Grunt工作流中使用nodemon


查看grunt-nodemon插件,将nodemon集成到你的项目的Grunt工作流中。


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

中文:


发音


nodemon应该如何发音:是读作node-mon、no-demon还是node-e-mon(像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.

中文:


设计原则


标志越少越好
在所有平台上都能工作
功能越少越好
让个人在nodemon的基础上进行构建
提供所有CLI功能作为API
贡献必须包含并通过测试
nodemon并不完美,CLI参数已经超出了我完全满意的范围,但也许有一天它可以减少一些。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值