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 5/25/2026
Here's how get-port finds an available port:
Core Strategy
The implementation has three main steps:
1. Test port availability [index.js:L47-L60]
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);
});
});
});
This creates a temporary TCP server and tries to listen on the requested port. If it succeeds, the port is available.
2. Iterate through preferred ports [index.js:L81-L88]
const portCheckSequence = function * (ports) {
if (ports) {
yield * ports;
}
yield 0; // Fall back to 0 if anything else failed
};
If you specify preferred ports, they're checked in order. If none work, port 0 is yielded, which tells the OS to assign a random available port.
3. Main loop with host checking [index.js:L89-L168]
The main getPorts function iterates through the port sequence. For each port, it:
- Skips excluded ports
- Checks availability via
getAvailablePort, which validates the port across all local hosts (unless a specific host is given) [index.js:L61-L78] - Checks if the port is already locked by the current process [index.js:L79-L80]
- If using
reserve: true, adds it toreservedPorts(permanent for the process lifetime); otherwise adds it tolockedPorts.young(released after 15-30 seconds) - Returns the first available port or throws an error if none found
FOLLOW_UPS:
- What does the reserve option actually do?
- How are locked ports tracked over time?
- What happens if all preferred ports fail?
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.