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/15/2026
The library finds an available port by attempting to bind a server to each candidate port and checking if the binding succeeds. Here's the core implementation:
Main port-checking logic [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 attempts to listen on the specified port. If successful, it resolves with the port number and closes the server. If binding fails (port is in use), the error is rejected.
Multi-host checking [index.js:L61-L78]:
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;
};
When no specific host is provided, it checks availability across all local hosts. If a specific host is given or port is 0 (random), it checks that single configuration.
Main function [index.js:L89-L168] iterates through preferred ports (or generates a random one), checks each using the above functions, manages port locking to prevent race conditions, and returns the first available port.
FOLLOW_UPS:
- What does the
reserveoption do exactly? - How does port locking prevent race conditions?
- What happens when no ports are available?
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.