RepoPilot

How does this find an available port? Show me the actual implementation.

About sindresorhus/get-port · 2 messages · last activity 7/13/2026

Question

How does this find an available port? Show me the actual implementation.

RepoPilot

Here's how the library finds an available port:

Core Port Checking Logic

The actual availability check happens in [checkAvailablePort] [index.js:L47-L60]. It:

  1. Creates a Node.js TCP server (net.createServer())
  2. Calls server.listen() with the target port/host options
  3. If successful, the port is available—it extracts the port number and closes the server
  4. If it fails (port already in use), the error is propagated
const checkAvailablePort = options =>
	new Promise((resolve, reject) => {
		const server = net.createServer();
		server.unref();
		server.on('error', reject);

		server.listen(options, () => {
			const {port} = server.address();
			server.close(() => {
				resolve(port);
			});
		});
	});

Multi-Host Availability Check

The [getAvailablePort] function [index.js:L61-L78] handles the complexity of checking across multiple local addresses:

  • If a specific host is provided or port is 0, it directly calls checkAvailablePort
  • Otherwise, it iterates through all local network interfaces and tries to bind the port on each one
  • If errors like EADDRNOTAVAIL or EINVAL occur (host-specific issues), it ignores them
  • Only if all hosts can bind the port does it return success

Main Flow

The main [getPort()] function [index.js:L89-L168] orchestrates this:

  1. Validates and normalizes options (port, exclude, reserve)
  2. Iterates through ports (preferred ports first, then random fallback)
  3. Calls getAvailablePort() for each candidate port
  4. Handles port locking (default 15-30s or permanent with reserve: true)
  5. Returns the first successfully available and unlocked port

FOLLOW_UPS:

  • What does the port locking mechanism do?
  • How are preferred ports handled when all are unavailable?
  • What does the portNumbers() helper function do?

Want to ask your own question?

Open chat for sindresorhus/get-port

Public Q&A. Generated by RepoPilot from the actual source of sindresorhus/get-port. AI answers can be incomplete or stale — verify before relying on them.