Node.js Series: Smoothly running it

So far in the series we have determined that there are a lot of advantages migrating to Node.js, from programmer’s team ease of adoption to performance, but it does need a few tools though.

When running your code directly from the node or npm executable, as it happens in any other languages, errors will occur, so you do not want your services braking down every time someone forgets to treat some exception. You will also like to continuously deliver code updates without clients experiencing downtime or performance degrading.

To achieve this you should probably be checking PM2 out, from Keymetrics.

This tool will not only keep your code running, but it also gives you strong professional tools for monitoring, managing and even debugging your running code.

If you already have Node.js installed, all you need to do is run this on your console:

npm install pm2 -g

Once you have it, it is easy to run you first code, if you have a javascript file that runs with node, let’s say it is called myservice.js, you can start it by running the code below. For this example I am using the code I posted previously, so go check it out!

So this is the part where it gets interesting. If you checkout line 3, you will see an URL, the ID here is obviously changed but once you run it on your machine and reach out to this link, you will get to the cloud monitoring page, and it looks like this:

As you can see this is obviously a paid feature, but it can really level up your game. If you have up to 4 processes you may use the free version and there is actually a lot to it, the real time monitoring it offers is quite useful, but there are a lot of features you may get with the paid one.

Back on the console, like I mentioned in the beginning, you will want to have your service fault proof and this is one of the pre-built features, in case your code fails, PM2 will automatically start restart it for you. Of course there needs to be a way you make sure your processes will start automatically in case you need to restart your server and to do that all you need to do is run this at your console:

pm2 startup

The console you return the next command you need to run in order to enable it to start on boot, in my case, this is what I got: