How does this find an available port? Show me the actual implementation.
How does this find an available port? Show me the actual implementation.
About sindresorhus/get-port · 2 messages · last activity 7/6/2026
The main implementation is in [index.js:L89-L168], which exports the default getPort function. Here's how it works:
High-level flow:
-
Parse options [index.js:L90-L116]: Converts the
portoption to an array (if needed) and validates theexcludeoption to ensure it's an iterable of numbers. -
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.
-
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
portis 0) - If successful and
reserveis true, add toreservedPorts; otherwise add tolockedPorts.young - Return the available port
-
Handle failures [index.js:L162-L165]: Only catch
EADDRINUSE(port in use) andEACCES(permission denied) errors; re-throw others.
Port checking logic [index.js:L61-L78] (getAvailablePort):
- If a specific host is given or
portis 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
checkAvailablePortfunction do exactly? - How does the
portCheckSequencefunction work? - What are the "local hosts" checked by default?
Want to ask your own question?
Open chat for sindresorhus/get-portPublic 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.