First, we'll start by installing Forever as a global module. Forever allows us to run scripts continuously whether it is written in Node.js or not. We will leverage this functionality to run our server continuously, and restart if any failure might occur.
Let's clear this out. Let's import the native HTTP module as HTTP. We will use this module to create our base server. Now, we'll create a server using the createrServer function exposed by the HTTP module.
The createServer takes in a function which is called for each incoming server request. The function takes in two parameters. The first one is the incoming request, and the second one is the response that we will populate with data and send back to client. Let's leave the function empty for now.
Let's get a reference to the server object, and we will name it server. Now, we can start listening on the server using the listen function and passing in a port number. I'll be using 8080. Feel free to use any open port.
Now, we'll start building a response to send back to the client. Let's write "Welcome to Egghead server" into the response stream. Then we'll end the response using the end function. This allows us to send the response back to the client.
Now, we'll start a server on Node and ping the server from our browser. If we navigate to our localhost 8080, we should get "Welcome to Egghead server." Now, we'll simulate a crash on our server, and then use Forever to fix this crashing issue.
We'll check for the incoming URL and break a server if it is /break. The crash can be simulated using process.exit, which kills the whole process, essentially bringing our server to a halt. Let's stop running the server and restart it.
If we navigate to the /break URL, we should break the server. As you can see, the Node process is also executed. Now, we'll start a server using Forever. We can go and check our server, whether it's running. As you can see, it's running.
Now, if we try to access the break path, we will break the server. We'll check if our server has restarted. Yes, it has restarted. If we break it again, as you can see, you can see that it has logged a script restarted in one and a script restarted at two.
Whenever you break the server, it's going to restart it again, making sure that your server's downtime will be as minimal as possible.