Is there a helper to generate a sequence of port numbers to try?
Is there a helper to generate a sequence of port numbers to try?
About sindresorhus/get-port · 2 messages · last activity 8/1/2026
Question
RepoPilot
Yes, there is. The portNumbers() helper function generates a sequence of port numbers in a given range.
According to [index.js:L169-L194], the portNumbers(from, to) function generates port numbers from from to to (inclusive) and returns an iterable:
export function portNumbers(from, to) {
if (!Number.isInteger(from) || !Number.isInteger(to)) {
throw new TypeError('`from` and `to` must be integer numbers');
}
if (from < minPort || from > maxPort) {
throw new RangeError(`'from' must be between ${minPort} and ${maxPort}`);
}
if (to < minPort || to > maxPort) {
throw new RangeError(`'to' must be between ${minPort} and ${maxPort}`);
}
if (from > to) {
throw new RangeError('`to` must be greater than or equal to `from`');
}
const generator = function * (from, to) {
for (let port = from; port <= to; port++) {
yield port;
}
};
return generator(from, to);
}
Both from and to must be integers in the range 1024...65535, and to must be greater than or equal to from. You can use it with getPort() by passing it to the port option [index.d.ts:L5]:
import getPort, {portNumbers} from 'get-port';
console.log(await getPort({port: portNumbers(3000, 3100)}));
// Will use any port from 3000 to 3100, otherwise fall back to a random port
FOLLOW_UPS:
- What validation does portNumbers() perform?
- Can I exclude specific ports from consideration?
- How does getPort handle port preference ordering?
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.