How can we check if a web service or a website is alive in nodejs? I am using node version 6.11 and express. I tried using isAlive in npm, but no luck there.
This is the one I tried, but it return false all the time.
var IsAlive = require('is-alive');
var isAlive = new IsAlive();
isAlive.add("http://google.com", 301, function (err) {
"use strict";
if (err) {
console.log(err);
}
});
setInterval(function () {
console.log(isAlive.isAlive("http://google.com"));
}, 2000);
console.log(isAlive.isAlive("http://google.com"));
I use using http as well like :
http.get('http://google.com', function (res) {
console.log(res);
}).on('error', function(e) {
console.log(e);
});;
And also like :
var request = require('request');
options = {method: 'HEAD', host: 'stackoverflow.com', port: 80, path: '/'},
req = http.request(options, function(r) {
console.log(JSON.stringify(r.headers));
});
req.end();
Tried using status code as well :
var http = require("http");
http.get({host: "google.com"},function(res){
if (res.statusCode ==200)
console.log ("running");
else
console.log ("not running");
});
Can we use any other method? basically my requirement is to check if a web service which is on a different server.
Finally, I cracked this. The problem as I doubt was since I was behind a proxy. So I modified the code given by @turmuka like :
var request = require('request');
var link = "https://nodejs.org/";
var proxyUrl = "http://" + user + ":" + password + "@" + host + ":" + port;
var proxiedRequest = request.defaults({'proxy': proxyUrl});
proxiedRequest(link , function (error, response, body) {
if(error){
console.log('Err: '+ error);
return false;
}
if(response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 202){
console.log(link + ' is up!!');
return false;
}
if(response.statusCode == 301 || response.statusCode == 302){
console.log(link + ' is redirecting us!!');
return false;
}
if(response.statusCode == 401){
console.log("you are unauthorized to " + link);
return false;
}else{
console.log(link + ' is down!!');
}
});
So basically, I need to set the proxy in the request to make sure the proxy won't be blocking the call. Thank you very much @turmuka for the answer, really helped me to figure it out.