In this video, learn how to automatically restart your node.js app using pm2 when the code for your app changes. You will also learn how to exclude files and directories from restarting your app (such as static assets, css, images, etc.).
One of the other cool features of PM2 is the ability to watch your application directories and restart your application if it detects a change to the file, much like if you were doing a push or had a hook on your version control system that pushed the code out when there was a change to a branch.
If we want to set that up, we go back into our config file, and we'll just add a new line here called Watch, and we'll set that equal to true.
Watch also comes with a counterpart, called Ignore Watch, and as the name implies, it will ignore whatever is defined here. It accepts an array, and inside the array you can put in file names, folder names, paths, and ReGex expressions, and everything that matches inside of the array will be ignored by the restart process.
Let's save, and exit out of that, and you'll see that the reason I chose the word to put files in there, is because inside my app one folder I have a subdirectory called files.
Let's go ahead and pull PM2 up now, with a PM2 start, and then our configuration object. We can see both apps launch.
Now, this time in our watching column, under app one, you can see that Watching is enabled, and since we did not define it for app two, it's set to disabled. Let's test that and see how it works.
We go into our app one, serve it as JS file. We can just make a little change here that says, "Hello from app one after a reload." If we save and quit, we get a PM2 list, you can see that the PID for app one changed from 7861 to 7876, while the PID for app two has remained the same at 7862, because watching is not set up for that.
If we switch over to our browser here and load the page, we get "hello from app one," after a reload, and then we switch back over to app two, and we still just get "hello from app two."
We also put in our Ignore Watch there, so we've got to test that and see how that works. If we edit a file inside of the files folder, we can just put "this is not valid HTML," save that and quit.
Now app one was running on a PID of 7876, so if we type PM2 list, we can see that even though we changed the file, it's still running on PID 7876, because that was in an ignored folder, and if we load our page, we still get "Hello from app one" after a reload, so everything's working just like we want.