RepoPilot

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

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

Question

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

RepoPilot

The main implementation is in [index.js:L89-L168], which exports the default getPort function. Here's how it works:

High-level flow:

  1. Parse options [index.js:L90-L116]: Converts the port option to an array (if needed) and validates the exclude option to ensure it's an iterable of numbers.

  2. Initialize port locking [index.js:L118-L129]: Sets up a timeout mechanism to release "young" locked ports after 15-30 seconds, moving them to "old" locked ports. This allows ports to be reused after a delay.

  3. Iterate through candidates [index.js:L131-L161]: For each port in the sequence (preferred ports first, then random ones):

    • Skip excluded ports
    • Call getAvailablePort() to check if the port is actually available on all local hosts
    • If the port is locked, retry with a new random port (only if port is 0)
    • If successful and reserve is true, add to reservedPorts; otherwise add to lockedPorts.young
    • Return the available port
  4. Handle failures [index.js:L162-L165]: Only catch EADDRINUSE (port in use) and EACCES (permission denied) errors; re-throw others.

Port checking logic [index.js:L61-L78] (getAvailablePort):

  • If a specific host is given or port is 0, check that single host
  • Otherwise, iterate through all local hosts and verify the port is available on all of them using checkAvailablePort()

Port locking mechanism: Ports are temporarily locked for 15-30 seconds to prevent race conditions. The reserve option makes the lock permanent for the process lifetime.

FOLLOW_UPS:

  • What does checkAvailablePort function do exactly?
  • How does the portCheckSequence function work?
  • What are the "local hosts" checked by default?

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.