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/18/2026
The get-port library finds an available port by attempting to bind to a port and observing whether it succeeds. Here's the core implementation:
Core Port Checking
The actual port availability check happens in [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 function creates a temporary Node.js TCP server and tries to listen on the given port and host. If it succeeds, the port is available—it then closes the server and returns the port number. If it fails, the error is rejected.
Checking Multiple Hosts
For preferred ports without a specific host, [index.js:L61-L78] shows how it checks across all local hosts:
const getAvailablePort = async (options, hosts) => {
if (options.host || options.port === 0) {
return checkAvailablePort(options);
}
for (const host of hosts) {
try {
await checkAvailablePort({port: options.port, host}); // eslint-disable-line no-await-in-loop
} catch (error) {
if (!['EADDRNOTAVAIL', 'EINVAL'].includes(error.code)) {
throw error;
}
}
}
return options.port;
};
If a specific host is provided or port is 0 (random), it checks once. Otherwise, it verifies the port is available on all local network interfaces by trying each one.
Main Logic
The main getPorts function [index.js:L89-L168] orchestrates the entire process: it iterates through preferred ports (or generates random ones), checks availability, handles the locking mechanism, and returns the first available port found.
FOLLOW_UPS:
- How does the port locking/reserve mechanism work?
- What does the
portNumbers()helper function do? - How are preferred ports prioritized when multiple are given?
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.