RepoPilot

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

About sindresorhus/get-port · 2 messages · last activity 6/29/2026

Question

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

RepoPilot

The core port-finding logic is implemented in index.js. Here's how it works:

Main entry point [index.js:L89-L168]: The getPorts function orchestrates the search:

  1. It normalizes the port option into an iterable
  2. Validates the exclude option (must be iterable numbers)
  3. Iterates through a port check sequence using portCheckSequence(ports)
  4. For each candidate port, it checks availability and handles locked ports
  5. Returns the first available port, or throws if none found

Port availability check [index.js:L47-L60]: The checkAvailablePort function does the actual detection:

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);
			});
		});
	});

It creates a temporary TCP server with net.createServer(), attempts to bind it with server.listen(), and if successful, immediately closes it and returns the port. If binding fails (error event), the promise rejects.

Multi-host checking [index.js:L61-L78]: When no specific host is provided, getAvailablePort iterates through all local hosts and validates the port works on each one before returning it.

Locking mechanism: The code maintains two sets (lockedPorts.young and lockedPorts.old) to prevent race conditions—ports are locked for 15-30 seconds by default, or indefinitely if reserve: true is used.

FOLLOW_UPS:

  • What does the portCheckSequence function do exactly?
  • How does the locking mechanism prevent port reuse?
  • Can you explain the reserve option in detail?

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.