reservePort
functionReserves a free TCP port by listening on it, so nothing else can take it until it's released, such as before passing it to a dev server or a test fixture. The preferred port is kept when it's free, and any free port is reserved when it's taken. Connections to the reserved port are closed at once, and the reservation doesn't keep the process running.
A child process that needs the port itself can't bind it while it's reserved, so release it right before starting the child. Another process can take the port in between.
reservePort(options?: IReservePortOptions): Promise<IPortReservation>Parameters
options?IReservePortOptionsThe preferred port and the address. The address defaults to 127.0.0.1.
Defaults to
{}.
Returns
Promise<IPortReservation>A promise that resolves to the reservation.
Throws
INVALID_PORTThe preferred port must be an integer from 1 to 65535.PORT_RESERVATION_FAILEDThe port couldn't be reserved.
import { reservePort } from 'jg-process';
const reservation = await reservePort({ preferredPort: 3000 });
console.log(`The port is ${reservation.port}`); // 3000, or another free port when it's taken
await reservation.release();