Solution 1
No status code
I’m not a Node.JS programmer, but I believe a ping would solve your problem.
A quick Google search found the package net-ping.
var ping = require ("net-ping");
var session = ping.createSession ();
session.pingHost (target, function (error, target) {
if (error)
console.log (target + ": " + error.toString ());
else
console.log (target + ": Alive");
});
Obs.: This solution is not very efficient for your case, as the server may be active, but the service may be down.
Solution 2
With status code
I found a package that makes the request and displays the code:
Package Request
var request = require('request');
request('http://answall.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Mostra o HTML da página inicial do StackOverflow.
}
});
It is not possible to only get the header or status code in an HTTP request, even because it is not the client that controls it.
The request is made as follows:
Client:
- Hello I want the page index.php
Server:
- No, here’s your page
Header: Status 200; Etc...
Body of the index.php page
Client:
- Hello, now I want the akjshlahsdasd.html page
Server:
- Sorry, I couldn’t find you.
Header: Status 404; Etc...
Body page 404
Client:
- Then give me the page serviceInternal.php
Server:
- Sorry, we’re having technical problems
Header: Status 500; Etc...
Body page 500
Client:
- Hmm, then give me database data.ini
Server:
- I’m sorry, you can’t access that file
Header: Status 403; Etc...
Body page 403
Note that even for request/server errors the body of an HTML page is returned, this can only be changed in the server’s own settings.
Solution 3
A third solution would be to check if the web port is open, but this port may vary on some servers. The default port is 80
, other servers use 8080
.
With the package Node-portscanner you can check if the door is open.
> var portscanner = require('portscanner')
undefined
> portscanner.checkPortStatus(443, 'www.google.com', console.log)
> null 'open'
> portscanner.checkPortStatus(80, 'www.google.com', console.log)
undefined
> null 'open'
Obs.: Just as in the first solution this is not very efficient, because the server may be active and the port opened, but the service may have fallen.
Receiving only server status is only possible if you create an empty page on the server, so you can request it for connection testing, only receiving the request header.
More details about the HTTP protocol:
- Understanding a little more about the HTTP protocol
- HTTP protocol
You can take a look in that question from Soen, maybe it’ll help. ;)
– KaduAmaral