Express 4 + pm2 watch not working
Asked Answered
S

1

23

I'm running pm2 with this:

pm2 start bin/www --watch ../

Problem is that when I update app.js in the root folder, it doesn't seem to be autorestarting node. Any ideas?

Scot answered 11/1, 2015 at 0:38 Comment(3)
I've been trying to figure this out myself. My thought is that it might be using the watch directory relative to the execution directory, which is the root directory of the project, so when you specify --watch ../, you're actually specifying the folder above where you actually want to watch. I haven't tried it myself, since I'm using pm2 on a production server, so I end up sshing in, git pulling the latest code, and then running pm2 restart www manually, which doesn't pertain to your problem.Tremolant
@BrandonAnzaldi: Discovered a solution. Posted as an answer below.Scot
Feb 2021 - Only following works now - https://mcmap.net/q/540961/-how-to-watch-and-reload-an-expressjs-app-with-pm2Pioneer
S
53

Figured out a solution:

//processes.json:
    {
      "apps" : [{
        "name"        : "someExpress4App",
        "script"      : "bin/www",
        "watch"       : "../",
        "log_date_format"  : "YYYY-MM-DD HH:mm Z",
      }]
    }

Put that on the root of your project, then run your pm2 as so:

pm2 start processes.json
Scot answered 12/1, 2015 at 0:28 Comment(7)
Should "watch" be a boolean value? enables the watch feature, defaults to "false". if true, it will restart your app everytime a file change is detected on the folder or subfolder of your appLippert
Doing that will watch the whole Express parent directory. That means if you use something like Webstorm that maintains a directory .idea, your pm2 will restart your server every time Webstorm will write in this directory. Same thing if you modify something in folder public... Instead of that, I propose to directly add directory that you want watch and your app.js "watch": ['core', 'other-folder', 'app.js']Sideline
@user1853777: it might be better to do "ignore_watch" : [".idea"] if you know exactly what's going to be constantly refreshed.Scot
I thought the other way: if you know exactly what you want watch, put it in "watch" ;). The main advantage is if someone use an other IDE, there is no change to do. And in ignore_watch you also have to list public folders. In my projects, I prefer to have only one folder for all server files, so it's easy to list in watch. Anyway, it's just a preference.Sideline
hey i am doing pm2 start first time and my json is like { "apps":[ { "name":"fp-back", "script":"/opt/nodeJs/fp-back/bin/www", "log_file":"/var/log/pm2/fp-back.log", "error_file":"/bar/log/pm2/fp-back-err.log", "watch":"/opt/nodeJs/fp-back/" } ] } what thing i am doing wrong i triple check this filePinter
How are you getting away with that last comma?Porringer
There is the explanation off all parameters: pm2.keymetrics.io/docs/usage/application-declarationZeralda

© 2022 - 2024 — McMap. All rights reserved.