Skip to content Skip to sidebar Skip to footer

How Can Check If Server And Port Is Available In Nodejs ?

I have project with is written with Nodejs. I need to know how to check if an IP with Port is working to connect to. EX: Check example1.com 443 =>true ; Check example1.com 8080

Solution 1:

The only way to know if a server/port is available is to try to actually connect to it. If you knew that the server responded to ping, you could run a ping off the server, but that just tells you if the host is running and responding to ping, it doesn't directly tell you if the server process you want to connect to is running and accepting connections.

The only way to actually know that it is running and accepting connections is to actually connect to it and report back whether it was successful or not (note this is an asynchronous operation):

var net = require('net');
varPromise = require('bluebird');

functioncheckConnection(host, port, timeout) {
    returnnewPromise(function(resolve, reject) {
        timeout = timeout || 10000;     // default of 10 secondsvar timer = setTimeout(function() {
            reject("timeout");
            socket.end();
        }, timeout);
        var socket = net.createConnection(port, host, function() {
            clearTimeout(timer);
            resolve();
            socket.end();
        });
        socket.on('error', function(err) {
            clearTimeout(timer);
            reject(err);
        });
    });
}

checkConnection("example1.com", 8080).then(function() {
    // successful
}, function(err) {
    // error
})

Solution 2:

One small correction after trying this code. Using socket.end() will always cause a connection reset error, thereby calling both resolve and reject. If you use this code in classic callback, use socket.destroy() instead

Post a Comment for "How Can Check If Server And Port Is Available In Nodejs ?"