I'm writing a status checker for a hosting company that I work for, we're wondering how we can check the status of a port using nodejs if it's possible. If not, can you suggest any other ideas like using PHP and reading STDOUT?
Yes, this is easily possible using the net
module. Here's a short example.
var net = require('net');
var hosts = [['google.com', 80], ['stackoverflow.com', 80], ['google.com', 444]];
hosts.forEach(function(item) {
var sock = new net.Socket();
sock.setTimeout(2500);
sock.on('connect', function() {
console.log(item[0]+':'+item[1]+' is up.');
sock.destroy();
}).on('error', function(e) {
console.log(item[0]+':'+item[1]+' is down: ' + e.message);
}).on('timeout', function(e) {
console.log(item[0]+':'+item[1]+' is down: timeout');
}).connect(item[1], item[0]);
});
Obviously it can be improved. For example, it currently breaks if a host cannot be resolved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With