RepoPilot

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

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

Question

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

RepoPilot

The implementation works in two layers:

1. Port CheckingcheckAvailablePort() [index.js:L47-L60]

Creates a TCP server and attempts to bind it to a port. If the server successfully listens, it extracts the assigned port number, closes the server, and resolves the promise with that port. If binding fails, the promise rejects with an error.

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

2. Host CheckinggetAvailablePort() [index.js:L61-L78]

If a specific host is provided or port is 0, it checks that single host. Otherwise, it iterates through all local hosts and validates the port can bind on each one. It returns the port once all hosts accept it.

3. Main LogicgetPorts() [index.js:L89-L168]

Iterates through preferred ports (or a random sequence if none specified). For each port candidate:

  • Skips excluded ports
  • Calls getAvailablePort() to check availability
  • Tracks locked ports (default 15-30 second expiration) vs. reserved ports (lifetime of process)
  • Returns the first available port that isn't already locked
  • Catches EADDRINUSE and EACCES errors and tries the next port

FOLLOW_UPS:

  • What does the reserve option actually do?
  • How does the portNumbers helper generate port sequences?
  • What's the portCheckSequence function for?

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.