Server Up or Down: Node.js


Using Node.js application we’ll check if a website is up and running or is it down.

check-website-up-or-down-nodejs

This is a simple application which pings server/URL and checks for the returned status code. Depending upon the status code returned, it displays message to the user on the console window.

JavaScript: Checking for status code
app.js

1
2
3
4
5
6
7
8
var http = require("http");
 
     http.get({host: "technotip.org"}, function(res){
    if( res.statusCode == 200 )
   console.log("This site is up and running!");
 else
   console.log("This site might be down "+res.statusCode);
   });

Here get() method of http object takes 2 parameters. First parameter is an object which contains host name, and the second parameter is a callback method, which gets its parameter from get() methods first parameter.

Using the res object we fetch the status code returned by the server. If the status code is 200, it means website is up and running. Else the website might be down.

Some times we get status code other than 200 and the site will still be up and running, in such cases we can display user-friendly messages and not web geek status codes!

JavaScript: Checking If website is Up or Down
app.js

1
2
3
4
5
6
7
8
9
10
11
var http = require("http");
 
 
  http.get({host: "www.technotip.org"}, function(res){
    if( res.statusCode == 200 || res.statusCode == 301 )
   console.log("Website Up and Running ..")
 else
  console.log("Website down");
 
console.log(http.STATUS_CODES[res.statusCode]);
   });

http object has yet another object nested inside it, called STATUS_CODES which has a list of status codes and its corresponding meaning: as key value pairs. Using this, we could fetch the description of the status code and display it to the user, which will be much more meaningful.

Check if the Server is Up or Down: Node.js



YouTube Link: https://www.youtube.com/watch?v=KQxVggPwDek [Watch the Video In Full Screen.]



Note: If we implement this as a web application, users could check if the website is down for everyone or is it just them.

You could even go through the entire list of all the status codes and implement a complete check and return the result to the user and not let the user guessing with the status code meaning.

Leave a Reply

Your email address will not be published. Required fields are marked *