How to check if there is an open port on the Node.js?

I have a server made on Node.js and a proxy server is defined.

http = require('http');
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});


this.httpServer = https.createServer(credentials, function(request, response) {
....

  proxy.web(request, response, { target: 'http://127.0.0.1:5001' });
}

If I have a proxied port, everything works fine. But if I do not have this port, I get an error. I can use it in the callback, but after that, when the port appears, proxying does not occur.

Probably I can make a new instance of the proxy server and it will work, but how do I check if there is an open port, so that if it does not exist, do not create a proxy and don't put error checking in this place ?

Author: Sergey, 2020-09-02

1 answers

NodeJS has a network module. In the code below, a connection is made to a socket, which results in the message yes/no.

const net = require("net");

class PortChecker {

    async testPort(port, host) {

        return new Promise((resolve, reject) => {
            const socket = new net.Socket();

            socket.on("connect", () => {
                socket.destroy();
                resolve("yes");
            });

            socket.on("timeout", () => {
                socket.destroy();
                resolve("no");
            });

            socket.on("error", () => {
                socket.destroy();
                resolve("no");
            });

            socket.connect(port, host);

        });
    }

}

let pc = new PortChecker;

pc.testPort(22, "127.0.0.1").then((result) => {
    console.log(`Is port open? ${result}`);
}).catch(err => {
    console.log("Fatal error:", err);
    process.exit(1);
});
 1
Author: Total Pusher, 2020-09-02 01:04:17