3

I'm trying run a simple app that checks the status of a URL using the http server module.

Basically this is the simple http server:

require('http').createServer(function(req, res) {
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.end('URL is OK');
    }).listen(4000);

Now within that I want to check the status of the URL using this section:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log("URL is OK") // Print the google web page.
  }
})

So basically I want to launch node , open a browser and display content with text saying "URL is OK". Then to refresh every 10 mins.

Any help is greatly appreciated.

lia1000
  • 159
  • 1
  • 4
  • 13

1 Answers1

13

The general strategy with node, is you have to place anything that depends on the result of an asynchronous operation inside your callback. In this case that means wait to send your response until you know if google's up.

For refreshing every 10 minutes, you will need to write some code into the page served, probably either using <meta http-equiv="refresh" content="30"> (30s), or one of the javascript techniques at Preferred method to reload page with JavaScript?

var request = require('request');
function handler(req, res) {
  request('http://www.google.com', function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log("URL is OK") // Print the google web page.
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.end('URL is OK');
    } else {
      res.writeHead(500, {'Content-Type': 'text/html'});
      res.end('URL broke:'+JSON.stringify(response, null, 2));
    }
  })
};

require('http').createServer(handler).listen(4000);
averydev
  • 5,717
  • 2
  • 35
  • 35
Plato
  • 10,812
  • 2
  • 41
  • 61
  • Thank you very much for this example. It works, however, I find that if the HTTP Status changes dynamically from say 200 to 500 then it does not refresh the page. You have to restart the http server. Is there a way to refresh the operation? – lia1000 Sep 28 '13 at 06:42
  • You need to include the page refresh code in the HTML that you send, in both responses (200 case and non-200 case). – Plato Sep 30 '13 at 01:04