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 6/29/2026
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:
- It normalizes the
portoption into an iterable - Validates the
excludeoption (must be iterable numbers) - Iterates through a port check sequence using
portCheckSequence(ports) - For each candidate port, it checks availability and handles locked ports
- 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
portCheckSequencefunction do exactly? - How does the locking mechanism prevent port reuse?
- Can you explain the
reserveoption in detail?
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.