From 5baf02a7cda91379327a8cd73c804fe5794c2591 Mon Sep 17 00:00:00 2001 From: Gregg Tavares Date: Sat, 18 Nov 2023 18:26:42 +0900 Subject: [PATCH] use listen instead of connect to find free port --- lib/get-free-port.js | 40 +++++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/lib/get-free-port.js b/lib/get-free-port.js index 61236ef..7d73e4a 100644 --- a/lib/get-free-port.js +++ b/lib/get-free-port.js @@ -1,32 +1,34 @@ -const { Socket } = require('net'); +const { Server } = require('net'); -// This works by trying to connect to a port. -// If connecting works then the port is in use -// If not the port is free +// This works by trying to listen on a port. +// If connecting works then the port is good to use. +// If not the port is busy, try another async function getFreePort(port) { return new Promise((resolve, reject) => { - const socket = new Socket(); - const timeout = () => { - resolve(port); - socket.destroy(); - }; + const server = new Server(); +// const timeout = () => { +// resolve(port); +// socket.destroy(); +// }; const next = () => { - socket.destroy(); + server.close(); resolve(getFreePort(++port)); }; - setTimeout(timeout, 10); - socket.on("timeout", timeout); - socket.on("connect", () => next()); - socket.on("error", error => { - if (error.code !== "ECONNREFUSED") - reject(error); - else - resolve(port); +// setTimeout(timeout, 1000); +// server.on("timeout", timeout); + server.on("listening", () => { + server.close(); + resolve(port); }); + server.on("error", next); - socket.connect(port, "0.0.0.0"); + server.listen({ + port, + host: "0.0.0.0", + exclusive: true, + }); }); };