forever vs nodemon vs pm2
Node.js 进程管理工具
forevernodemonpm2类似的npm包:

Node.js 进程管理工具

Node.js 进程管理工具用于监控和管理 Node.js 应用程序的运行状态,确保它们在崩溃或意外关闭后能够自动重启。这些工具提供了开发和生产环境中所需的稳定性和可靠性,帮助开发者更高效地管理应用程序的生命周期。通过使用这些工具,开发者可以专注于编写代码,而不必担心应用程序的运行状态和崩溃问题。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
forever013,856150 kB342-MIT
nodemon026,691219 kB111 个月前MIT
pm2043,024838 kB1,0984 个月前AGPL-3.0

功能对比: forever vs nodemon vs pm2

自动重启

  • forever:

    Forever 提供基本的自动重启功能,当应用程序崩溃时会自动重启,确保应用程序的持续运行。

  • nodemon:

    Nodemon 主要用于开发环境,能够监控文件变化并在文件修改时自动重启应用程序,极大提高开发效率。

  • pm2:

    PM2 提供强大的自动重启功能,支持集群模式,可以在多核系统上运行多个实例,确保高可用性和负载均衡。

日志管理

  • forever:

    Forever 提供基本的日志记录功能,可以将输出和错误日志保存到文件中,方便后续查看和调试。

  • nodemon:

    Nodemon 不提供日志管理功能,主要关注于开发过程中的自动重启,适合快速迭代开发。

  • pm2:

    PM2 提供全面的日志管理功能,可以实时查看日志,支持日志轮转和持久化,方便生产环境的监控和维护。

集群支持

  • forever:

    Forever 不支持集群模式,主要用于单实例应用程序的管理。

  • nodemon:

    Nodemon 也不支持集群模式,主要用于开发环境中的单实例应用程序。

  • pm2:

    PM2 支持集群模式,可以在多核 CPU 上运行多个实例,提升应用程序的性能和可用性。

监控功能

  • forever:

    Forever 提供基本的监控功能,可以查看应用程序的运行状态,但功能相对简单。

  • nodemon:

    Nodemon 不提供监控功能,专注于文件变化的检测和自动重启。

  • pm2:

    PM2 提供强大的监控功能,可以实时监控应用程序的 CPU 和内存使用情况,并提供 Web 界面和命令行工具进行管理。

使用场景

  • forever:

    Forever 适合简单的 Node.js 应用程序,特别是在开发和测试阶段,使用简单,配置方便。

  • nodemon:

    Nodemon 适合开发环境,特别是需要频繁修改代码的场景,能够快速反馈修改结果。

  • pm2:

    PM2 适合生产环境,尤其是需要高可用性和负载均衡的大型应用程序,提供全面的管理和监控功能。

如何选择: forever vs nodemon vs pm2

  • forever:

    选择 Forever 如果你需要一个简单的命令行工具来确保你的 Node.js 应用程序持续运行,适合小型项目或开发环境。它的配置简单,适合快速部署和测试。

  • nodemon:

    选择 Nodemon 如果你在开发过程中需要自动重启应用程序,适合开发环境。它监控文件变化并自动重启应用程序,极大提高开发效率。

  • pm2:

    选择 PM2 如果你需要一个功能强大的进程管理器,适合生产环境。PM2 提供负载均衡、集群模式、日志管理和监控功能,是大型应用程序的理想选择。

forever的README

forever

Join the chat at https://gitter.im/foreverjs/forever

Version npmnpm DownloadsBuild StatusDependenciesInline docs

NPM

A simple CLI tool for ensuring that a given script runs continuously (i.e. forever). Note that this project currently fully depends on the community for implementing fixes and new features. For new installations we encourage you to use pm2 or nodemon

Installation

  $ [sudo] npm install forever -g

Note: If you are using forever programmatically you should install forever-monitor.

  $ cd /path/to/your/project
  $ [sudo] npm install forever-monitor

Usage

There are two ways to use forever: through the command line or by using forever in your code. Note: If you are using forever programatically you should install forever-monitor.

Command Line Usage

You can use forever to run scripts continuously (whether it is written in node.js or not).

Example

forever start app.js

Options

  $ forever --help
  usage: forever [action] [options] SCRIPT [script-options]

  Monitors the script specified in the current process or as a daemon

  actions:
    start               Start SCRIPT as a daemon
    stop                Stop the daemon SCRIPT by Id|Uid|Pid|Index|Script
    stopall             Stop all running forever scripts
    restart             Restart the daemon SCRIPT
    restartall          Restart all running forever scripts
    list                List all running forever scripts
    config              Lists all forever user configuration
    set <key> <val>     Sets the specified forever config <key>
    clear <key>         Clears the specified forever config <key>
    logs                Lists log files for all forever processes
    logs <script|index> Tails the logs for <script|index>
    columns add <col>   Adds the specified column to the output in `forever list`. Supported columns: 'uid', 'command', 'script', 'forever', 'pid', 'id', 'logfile', 'uptime'
    columns rm <col>    Removed the specified column from the output in `forever list`
    columns set <cols>  Set all columns for the output in `forever list`
    columns reset       Resets all columns to defaults for the output in `forever list`
    cleanlogs           [CAREFUL] Deletes all historical forever log files

  options:
    -m  MAX          Only run the specified script MAX times
    -l  LOGFILE      Logs the forever output to LOGFILE
    -o  OUTFILE      Logs stdout from child script to OUTFILE
    -e  ERRFILE      Logs stderr from child script to ERRFILE
    -p  PATH         Base path for all forever related files (pid files, etc.)
    -c  COMMAND      COMMAND to execute (defaults to node)
    -a, --append     Append logs
    -f, --fifo       Stream logs to stdout
    -n, --number     Number of log lines to print
    --pidFile        The pid file
    --uid            DEPRECATED. Process uid, useful as a namespace for processes (must wrap in a string)
                     e.g. forever start --uid "production" app.js
                         forever stop production
    --id             DEPRECATED. Process id, similar to uid, useful as a namespace for processes (must wrap in a string)
                     e.g. forever start --id "test" app.js
                         forever stop test
    --sourceDir      The source directory for which SCRIPT is relative to
    --workingDir     The working directory in which SCRIPT will execute
    --minUptime      Minimum uptime (millis) for a script to not be considered "spinning"
    --spinSleepTime  Time to wait (millis) between launches of a spinning script.
    --colors         --no-colors will disable output coloring
    --plain          Disable command line colors
    -d, --debug      Forces forever to log debug output
    -v, --verbose    Turns on the verbose messages from Forever
    -s, --silent     Run the child script silencing stdout and stderr
    -w, --watch      Watch for file changes
    --watchDirectory Top-level directory to watch from
    --watchIgnore    To ignore pattern when watch is enabled (multiple option is allowed)
    -t, --killTree   Kills the entire child process tree on `stop`
    --killSignal     Support exit signal customization (default is SIGKILL),
                     used for restarting script gracefully e.g. --killSignal=SIGTERM
                     Any console output generated after calling `forever stop/stopall` will not appear in the logs
    -h, --help       You're staring at it

  [Long Running Process]
    The forever process will continue to run outputting log messages to the console.
    ex. forever -o out.log -e err.log my-script.js

  [Daemon]
    The forever process will run as a daemon which will make the target process start
    in the background. This is extremely useful for remote starting simple node.js scripts
    without using nohup. It is recommended to run start with -o -l, & -e.
    ex. forever start -l forever.log -o out.log -e err.log my-daemon.js
        forever stop my-daemon.js

There are several examples designed to test the fault tolerance of forever. Here's a simple usage example:

  $ forever -m 5 examples/error-on-timer.js

JSON Configuration Files

In addition to passing forever the path to a script (along with accompanying options, described above), you may also pass forever the path to a JSON file containing these options. For example, consider an application with the following file structure:

.
├── forever
│   └── development.json
└── index.js

// forever/development.json
{
	// Comments are supported
    "uid": "app",
    "append": true,
    "watch": true,
    "script": "index.js",
    "sourceDir": "/home/myuser/app",
    "logFile": "/home/myuser/logs/forever.log",
    "outFile": "/home/myuser/logs/out.log",
    "errFile": "/home/myuser/logs/error.log"
}

This application could be started with forever, as shown below:

$ forever start ./forever/development.json

Absolute paths to such configuration files are also supported:

$ forever start /home/myuser/app/forever/development.json

Note: Forever parses JSON configuration files using shush, allowing the use of in-line comments within such files.

Multi-App Configuration Files

JSON configuration files can also be used to define the startup options for multiple applications, as shown below.

[
  {
    // App1
    "uid": "app1",
    "append": true,
    "watch": true,
    "script": "index.js",
    "sourceDir": "/home/myuser/app1"
  },
  {
    // App2
    "uid": "app2",
    "append": true,
    "watch": true,
    "script": "index.js",
    "sourceDir": "/home/myuser/app2",
    "args": ["--port", "8081"]
  }
]

Using In Your Code

The forever module exposes some useful methods to use in your code. Each method returns an instance of an EventEmitter which emits when complete. See the forever cli commands for sample usage.

Remark: As of forever@0.6.0 processes will not automatically be available in forever.list(). In order to get your processes into forever.list() or forever list you must instantiate the forever socket server:

  forever.startServer(child);

This method takes multiple forever.Monitor instances which are defined in the forever-monitor dependency.

forever.load (config)

Synchronously sets the specified configuration (config) for the forever module. There are two important options:

OptionDescription  Default
rootDirectory to put all default forever log filesforever.root
pidPathDirectory to put all forever *.pid files[root]/pids
sockPathDirectory for sockets for IPC between workers[root]/sock
loglengthNumber of logs to return in forever tail100
columnsArray of columns to display when format is trueforever.config.get('columns')
debugBoolean value indicating to run in debug modefalse
streamBoolean value indicating if logs will be streamedfalse

forever.start (file, options)

Starts a script with forever. The options object is what is expected by the Monitor of forever-monitor.

forever.startDaemon (file, options)

Starts a script with forever as a daemon. WARNING: Will daemonize the current process. The options object is what is expected by the Monitor of forever-monitor.

forever.stop (index)

Stops the forever daemon script at the specified index. These indices are the same as those returned by forever.list(). This method returns an EventEmitter that raises the 'stop' event when complete.

forever.stopAll (format)

Stops all forever scripts currently running. This method returns an EventEmitter that raises the 'stopAll' event when complete.

The format parameter is a boolean value indicating whether the returned values should be formatted according to the configured columns which can set with forever columns or programmatically forever.config.set('columns').

forever.list (format, callback)

Returns a list of metadata objects about each process that is being run using forever. This method will return the list of metadata as such. Only processes which have invoked forever.startServer() will be available from forever.list()

The format parameter is a boolean value indicating whether the returned values should be formatted according to the configured columns which can set with forever columns or programmatically forever.config.set('columns').

forever.tail (target, options, callback)

Responds with the logs from the target script(s) from tail. There are two options:

  • length (numeric): is is used as the -n parameter to tail.
  • stream (boolean): is is used as the -f parameter to tail.

forever.cleanUp ()

Cleans up any extraneous forever *.pid files that are on the target system. This method returns an EventEmitter that raises the 'cleanUp' event when complete.

forever.cleanLogsSync (processes)

Removes all log files from the root forever directory that do not belong to current running forever processes. Processes are the value returned from Monitor.data in forever-monitor.

forever.startServer (monitor0, monitor1, ..., monitorN)

Starts the forever HTTP server for communication with the forever CLI. NOTE: This will change your process.title. This method takes multiple forever.Monitor instances which are defined in the forever-monitor dependency.

Logging and output file locations

By default forever places all of the files it needs into /$HOME/.forever. If you would like to change that location just set the FOREVER_ROOT environment variable when you are running forever:

FOREVER_ROOT=/etc/forever forever start index.js

Make sure that the user running the process has the appropriate privileges to read & write to this directory.

Run Tests

  $ npm test

License: MIT

Author: Charlie Robbins

Maintainer: Igor Savin

Contributors: Fedor Indutny, James Halliday, Charlie McConnell, Maciej Malecki, John Lancaster