I am working on the Node.js web application to check the status code of the websites running, I have been able to get the status code and get the response, and catch but I need to handle the error through the event handler.
In this code am not able to fetch the status code value in one of the variable as am not able get the value outside of the http.request function and store that in a variable, there are other questions that are related to access the variable using callbacks bit didn't help me when I tried the same.
var http = require('http');
var statcode;
This is the below code in the handlebar helper function that I am calling to test the particular site
sitefunction: function ()
{
var options = {
method: 'HEAD',
port: 84,
host: 'example-site',
path:'/XYZ/'
};
var req = http.request(options, function(res) {
// n1 = 7;
});
statcode = req.statusCode;
req.on('error', function(err) {
if(err.code == 'ENOTFOUND')
{
return 'Server Unreachable'
}
else
{
//console.log(err);
}
});
if (statcode == 200)
return 'Website Running fine'+statcode+'';
else if(statcode == 304)
return 'Website Running fine';
else if (statcode == 0)
return 'Status code 0'
else
return "Please check the http code "+statcode+" if any error";
//return n1;
}
For the above code am getting error unable to read the property for the req.StatusCode
, whereas with the function below without the error handler am getting the desired response code, but the program terminates with an error when the connection error occurs.
Here is the below code that works without error handler:
In this code am able to fetch the status code and store it a variable statcode but I need to handle the error when the host is not reachable else the program terminates.
txyzfunction: function ()
{
var options = {
method: 'HEAD',
port: 84,
host: 'example-site2',
path:'/xyz/'
};
http.request(options, function(res) {
// n1 = 7;
});
statcode = res.statusCode
if ( statcode == 200)
return 'Website Running fine';
else if( statcode == 304)
return 'Website Running fine';
else if ( statcode == 0)
return 'Status code 0'
else
return "Please check the http code "+ statcode+" if any error";
//return n1;
}
Is there a clean way to read the status code and handle the error event as well? With the second function code, I can't handle the error event, as with the function code am not able to read the status code properly.