Question
How does this find an available port? Show me the actual implementation.
About sindresorhus/get-port · 2 messages · last activity 7/13/2026
How does this find an available port? Show me the actual implementation.
Here's how the library finds an available port:
The actual availability check happens in [checkAvailablePort] [index.js:L47-L60]. It:
net.createServer())server.listen() with the target port/host optionsconst 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);
});
});
});
The [getAvailablePort] function [index.js:L61-L78] handles the complexity of checking across multiple local addresses:
host is provided or port is 0, it directly calls checkAvailablePortEADDRNOTAVAIL or EINVAL occur (host-specific issues), it ignores themThe main [getPort()] function [index.js:L89-L168] orchestrates this:
getAvailablePort() for each candidate portreserve: true)FOLLOW_UPS:
portNumbers() helper function do?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.