How to automatically reload Node.js project when using pm2

Mr.Dung picture Mr.Dung · Apr 21, 2015 · Viewed 19.6k times · Source

I am currently programming Node.js with Express.js, and every time I change a line of code in the file router or app, I need to type the command:

pm2 reload id_project.

How do I make pm2 auto-reload the project when a file is changed?

Answer

Rogier Spieker picture Rogier Spieker · Jun 7, 2015

You need to start your pm2 project with the --watch option:

pm2 start <script|name|id> --watch

Where <script|name|id> refers to:

  • script the path to the script you want to let pm2 handle
  • name the name of the configuration in the "ecosystem" file
  • id refers to an already running application using pm2, which can be obtained using pm2 list (note that this would actually require a restart instead of start, so it's probably the least desirable of the options)

You could also specify which files/directories to ignore:

pm2 start <script> --watch --ignore-watch "node_modules"

Watch & Restart

Or create an "ecosystem" json file describing how you want pm2 to treat your project:

{
  "name": "project_name",
  "script": "index.js",
  "watch": true,
  "ignore_watch": ["node_modules"]
}

JSON options