Skip to content

Commit

Permalink
feat: export waitForPort
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Feb 25, 2022
1 parent ccf8583 commit 1c42832
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,16 @@ or npm install get-port-please

```js
// ESM
import { getPort, checkPort, getRandomPort } from 'get-port-please'
import { getPort, checkPort, getRandomPort, waitForPort } from 'get-port-please'

// CommonJS
const { getPort, checkPort, getRandomPort } = require('get-port-please')
const { getPort, checkPort, getRandomPort, waitForPort } = require('get-port-please')
```

```ts
function getPort(options?: GetPortOptions): Promise<number>
function checkPort(port: number, host?: string): Promise<number | false>
getPort(options?: GetPortOptions): Promise<number>
checkPort(port: number, host?: string): Promise<number | false>
waitForPort(port: number, options): Promise<number | false>
```

Try sequence is: port > ports > memo > random
Expand Down
18 changes: 17 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export async function getRandomPort (host: HostAddress) {
return port
}

export async function checkPort (port: PortNumber, host: HostAddress | HostAddress[] | undefined = process.env.HOST): Promise<PortNumber|false> {
export async function checkPort (port: PortNumber, host: HostAddress | HostAddress[] = process.env.HOST): Promise<PortNumber|false> {
if (!host) {
host = getLocalHosts([undefined /* default */, '0.0.0.0'])
}
Expand All @@ -86,6 +86,22 @@ export async function checkPort (port: PortNumber, host: HostAddress | HostAddre
return port
}

export interface WaitForPortOptions {
host?: HostAddress
delay?: number
retries?: number
}
export async function waitForPort (port: PortNumber, opts: WaitForPortOptions = {}) {
const delay = opts.delay || 500
const retries = opts.retries || 4
for (let i = retries; i > 0; i--) {
if (await _checkPort(port, opts.host) === false) {
return
}
}
throw new Error(`Timeout waiting for port ${port} after ${retries} retries with ${delay}ms interval.`)
}

// ----- Internal -----

function _checkPort (port: PortNumber, host: HostAddress): Promise<PortNumber|false> {
Expand Down

0 comments on commit 1c42832

Please sign in to comment.