pm2 - How to start if not started, kill and start if started pm2 - How to start if not started, kill and start if started windows windows

pm2 - How to start if not started, kill and start if started


Use this:

pm2 delete main.js 2> /dev/null &&  pm2 start main.js

This part: 2> /dev/null - will simply redirect the stderr to the /dev/null, meaning to nowhere.


It does not seem there is a "single command" way to do this, which is rather important in many development environments, so here are some options:

put soyuka's suggestion on one line.

pm2 stop myprocess; pm2 start myprocess.js

This will output errors, but it will work.

They also have this option built into their ecosystem tools. To use this, go into the folder you are working with and run

pm2 ecosystem

This will generate a file ecosystem.config.js which you will need to make sure your name and script are correct within.

You can then use the command:

pm2 startOrReload ecosystem.config.js

I, however also want to see my logging, so I use this command:

pm2 flush && pm2 startOrReload ecosystem.config.js && pm2 log

This will also flush the logs so you are not seeing old logs.


You can do something like this

pm2 delete your_app_name || : && pm2 start index.js -i 1 --name 'your_app_name'

The : is a null operator that returns 0 success exit code. So whatever happens, pm2 start command will execute (even if pm2 delete fails, for the case where the app does not exist yet).