I made this promise function which makes a connection to a specific host however I need to have the remoteAddress to be present in the logs when there is a timeout or an error. It seems like this gets deleted from the object. This is my code:
const makeTCPConnection = async (host, portNumber) =>
new Promise((resolve, reject) => {
const client = new Socket();
let remoteAddress;
let localAddress;
const timeout = 2;
client.setTimeout(timeout);
client.connect(portNumber, host, () => {
console.log("TCP connection established", {
host,
portNumber,
localAddress,
remoteAddress
});
});
client.on("connect", () => {
localAddress = client.localAddress;
remoteAddress = client.remoteAddress;
// client.destroy();
resolve();
});
client.on("close", () => {
client.destroy();
resolve();
});
client.on("drain", () => {
client.destroy();
resolve();
});
client.on("end", () => {
client.destroy();
resolve();
});
client.on("timeout", (error) => {
console.error("TCP client timeout after 1s", {
error,
host,
portNumber,
localAddress,
remoteAddress
});
// client.destroy();
reject(error);
});
client.on("error", (error) => {
console.error("TCP client connection error", {
error,
host,
portNumber,
localAddress,
remoteAddress
});
client.destroy();
reject(error);
});
});
I been testing this with timeout mainly, I tried to remove the client.destroy() on timeout event but then I get like 4 logs before I get the one with remoteAddress on it. The same thing is happening with localAddress.
Anyone have any ideas?