The net.Socket () object needs to be created periodically in nodejs, which takes up a lot of CPU/ memory. How should it be freed?

wrote a tool function for different modules to check the network on or off. Some modules will call this function periodically every few seconds. As a result, after a long time, the CPU and memory usage are very high, which is initially determined to be caused by new net.Socket (). How should this object be released?

var net = require("net");

export function detectNetwork(host, port, timeout=1000) {
    return new Promise(function (resolve, reject) {
        var testsocket = require("socket.io-client")("http://localhost");
        // testsocket.on("connect", function(){});

        var client = new net.Socket();
        client.setTimeout(timeout);

        client.connect(port, host)

        // onceon
        client.on("connect", function() {
          resolve({"localAddress": client.localAddress,
                   "localPort": client.localPort});
        })

        client.on("error", function(e) {
          reject(e);
        })

        client.on("timeout", () => {
          var e = {"code": "ETIMEDOUT",
               "errno": "ETIMEDOUT",
               "message": "connect ETIMEDOUT " + host + ":" + port,
               "address": host,
               "port": port,
               "syscall": "connect"
              }
          reject(e);
        });
    });
};

Aug.27,2021

const socket = new net.Socket();
export function xxx(host,port,timeout=10000) {
    client.connect();
}

try it?

Menu