Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - How to check status of a URL within a http request

Tags:

node.js

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.

like image 983
lia1000 Avatar asked Feb 03 '26 17:02

lia1000


1 Answers

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);
like image 106
Plato Avatar answered Feb 06 '26 10:02

Plato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!