Skip to content

Commit

Permalink
feat: alternative port and verbose logging
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 7, 2022
1 parent 779f3b7 commit 49200e6
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"@types/node": "latest",
"c8": "latest",
"eslint": "latest",
"jiti": "^1.14.0",
"standard-version": "latest",
"typescript": "latest",
"unbuild": "latest",
Expand Down
2 changes: 2 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 22 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export interface GetPortOptions {
port: number
ports: number[]
portRange: [from: number, to: number]
alternativePortRange: [from: number, to: number]
host: string
memoDir: string
memoName: string
Expand All @@ -37,7 +38,8 @@ export async function getPort (config?: GetPortInput): Promise<PortNumber> {
random: false,
port: parseInt(process.env.PORT || '') || 3000,
ports: [],
portRange: [3000, 3100],
portRange: [],
alternativePortRange: [3000, 3100],
host: undefined,
memoName: 'port',
verbose: false,
Expand Down Expand Up @@ -76,7 +78,15 @@ export async function getPort (config?: GetPortInput): Promise<PortNumber> {
}

// Try to find a port
const availablePort = await findPort(portsToCheck, options.host, options.verbose)
let availablePort = await findPort(portsToCheck, options.host, options.verbose, false)

// Try fallback port range
if (!availablePort) {
availablePort = await findPort(options.alternativePortRange, options.host, options.verbose)
if (options.verbose) {
log(`Unable to find an available port (tried ${portsToCheck.join(', ')}). Using alternative port:`, availablePort)
}
}

// Persist
await setMemo({ [memoKey]: availablePort }, memoOptions)
Expand Down Expand Up @@ -173,12 +183,20 @@ function getLocalHosts (additional?: HostAddress[]): HostAddress[] {
return Array.from(hosts)
}

async function findPort (ports: number[], host?: HostAddress, _verbose?: boolean): Promise<PortNumber> {
async function findPort (ports: number[], host?: HostAddress, _verbose: boolean = false, _random: boolean = true): Promise<PortNumber> {
for (const port of ports) {
const r = await checkPort(port, host, _verbose)
if (r) {
return r
}
}
return getRandomPort(host)
if (_random) {
const randomPort = await getRandomPort(host)
if (_verbose) {
log(`Unable to find an available port (tried ${ports.join(', ')}). Using random port:`, randomPort)
}
return randomPort
} else {
return 0
}
}

0 comments on commit 49200e6

Please sign in to comment.