Raspberry Pi and JavaScript — A simple site health check monitor — Part 2

This is part 2 of writing a simple health check monitor with Raspberry Pi and JavaScript. If you have not read part 1, please read that and then continue. You can read part 1 by clicking here

Requirement:

We need to write a program which pings a website at specific intervals and gets the HTTP status. If the status is more than 400 (Normally the HTTP status for a webpage will be 200 or 304 if the site is working fine) then we need to trigger a mail to a specific mail id.

Setting up the project:

  1. Connect the raspberry pi to your computer as mentioned in the previous article
  2. Go to Terminal and type the command arp -a to list the devices connected
  3. Login into the raspberry pi using ssh pi@192.168.2.2 (provided 192.168.2.2 is the IP of your raspberry)
  4. The above command will ask for a password for raspberry Pi. Enter the password for the raspberrypi. (Usually it is ‘raspberry’ if you have not changed the default password)
  5. If the login is successful you will see in the command line pi@raspberrypi:~ $
  6. Create a directory for our project. For example mkdir site-health-check
  7. Enter into the directory using cd site-health-check
  8. Initialise the directory using the command npm init
  9. The above command will ask for details like name, author..etc. Enter the details. If you are not sure what to enter, just press the enter key.
  10. Now the project set up is over. Lets get our hands dirty by writing the code

Getting status of a website:

Lets say we want to notify us when this medium blog is down. (You can choose your company or personal website). We can use the https module of nodejs to send a request to this medium blog and analyse the response.

// Require HTTPS module. Use http if your site is accessed via HTTP instead of HTTPS
let http = require(‘https’);
// Function to request our site
let requestSite = function requestSite() {
// We need to request the URL medium.com/til-js
let options = {
host: 'medium.com',
path: '/til-js',
method: 'GET'
}
// Initiate the HTTP GET request to access the site medium.com/til-js
let request = http.request(
options, function(response) {
 // Check the reponse code. If it is greater than 400, its an error
if(parseInt(response.statusCode, 10) >= 400) {
 // Send mail. Will be implemented later
 }
});

// Send mail on error
request.on(‘error’, function(e) {

// Send mail. Will be implemented later
 });
 request.end();
}
requestSite();

The above code will request the URL medium.com/til-js using HTTPS protocol. After the GET request, we check the statusCode of the response. If it is more than 400, then its an error. (Some might argue that status code above 500 should be notified since 4XX is a client error and 5xx is a server error. Since our request is a valid one, we are sure that it won’t create a 4XX error. So if a 4XX error occurs (say 404) then there is some problem and we want to get notified about that)

Sending mail on error:

Let us assume that we want to send a mail from our gmail address when there is an error. We use a node package called ‘node-mailer’ to send mail.

Before that we need to get a pass key from Gmail so that we can send the email through our program. To get a passkey from gmail, you need to first set up 2 step authentication to your gmail account. A 2 step authentication makes your account more secure. You can set up a 2 step authentication using the link : https://www.google.com/landing/2step/

If your Gmail account has 2 step authentication already enabled, you can proceed to create a password specific to our program that we are writing. You can create a app password using the link https://security.google.com/settings/security/apppasswords

After signing into the above page, click on the option ‘Mail’ from the first drop down and click ‘Other’ from the second drop down and type ‘My Raspberry Pi’ and click ‘Generate’. This will create an app password for you. Please copy the password as it won’t be shown the second time. If you lost the password, you have to create another app to get a new password.

If you followed the above procedures you will see a window like this:

After you copy the above password and click done, you can see an entry for the app in your account as below:

Now you can use the above password and your email address to send an email to any mail id through our program. Without delay, let’s look at the code to send email:

// Require HTTPS module. Use http if your site is accessed via HTTP instead of HTTPS
let http = require(‘https’);
// Require node mailer for sending emails
let mailer = require('nodemailer');
// Function to request our site
let requestSite = function requestSite() {
// We need to request the URL medium.com/til-js
let options = {
host: 'medium.com',
path: '/til-js',
method: 'GET'
}
// Configure the mailer first
let smtpTransport = mailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: 'EMAIL_ADDRESS_YOU_USED_TO_CREATE_PASSWORD_ABOVE',
pass: 'PASSWORD_YOU_GOT_FROM_ABOVE_STEP'
}
});
// Create a mail template with from, to and subject
// To address can also be your email address
let mail= {
from: 'ABOVE_EMAIL_ADDRESS',
to: 'ANY_EMAIL_ADDRESS_THAT_YOU_WANT_TO_BE_NOTIFIED',
subject: 'Site medium.com/til-js is down',
html: ''
}
// Initiate the HTTP GET request to access the site medium.com/til-js
let request = http.request(
options, function(response) {
// Check the reponse code. If it is greater than 400, its an error
if(parseInt(response.statusCode, 10) >= 400) {
  // Mail implementation
// Send the mail
smtpTransport.sendMail(mail, function(error, response) {
// Useful for finding the error
console.log('error is ', error);
smtpTransport.close();
});
}
});

// Send mail on error
request.on(‘error’, function(e) {
// Send the error object to mail body
mail.html += 'Error in get request. '+ e;
   // Send mail.
smtpTransport.sendMail(mail, function(e) {
smtpTransport.close();
})
});
request.end();
}
requestSite();

Save the above code as index.js file. Run using the command node index.js

If you get an error saying that the module ‘node-mailer’ cannot be found, try npm install node-mailer -save

The above command will install node-mailer and save it as a project dependency in your package.json file. But the above code will send the request only once. Lets say we want to ping our site every 1 minute, so we can rewrite the above code in a setInterval with a time limit of 60000.

I have moved some items to a separate config file and uploaded the whole code in my github repo https://github.com/subramaniashiva/site-health-check-raspberry/

Make sure you start the program by typing node index.js and keep the raspberry pi running. The program will send a request every 1 minute and triggers you a mail when the site is down.

I hope you have understood how to write a simple site health check monitor using Raspberry Pi and JavaScript. Thoughts, questions, comments? Please write below. Happy to interact.

Show your support

Clapping shows how much you appreciated Siva Subramaniam’s story.