Skip to content

Commit

Permalink
use listen instead of connect to find free port
Browse files Browse the repository at this point in the history
  • Loading branch information
greggman committed Nov 18, 2023
1 parent 324a3c5 commit 5baf02a
Showing 1 changed file with 21 additions and 19 deletions.
40 changes: 21 additions & 19 deletions lib/get-free-port.js
Original file line number Diff line number Diff line change
@@ -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,
});
});
};

Expand Down

0 comments on commit 5baf02a

Please sign in to comment.