Skip to content
This repository has been archived by the owner on Jan 2, 2025. It is now read-only.

Commit

Permalink
find available port (#86)
Browse files Browse the repository at this point in the history
  • Loading branch information
DamilolaAlao authored Jul 11, 2024
1 parent c8b4ce1 commit 67e57f5
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
30 changes: 30 additions & 0 deletions lib/cmd-fns/dev/find-available-port.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import net from 'net'

const MAX_PORT = 65535 // Maximum valid port number

export const findAvailablePort = async (startPort: number): Promise<number> => {
let port = startPort

while (port <= MAX_PORT) {
if (!(await isPortInUse(port))) {
return port
}
port++
}

throw new Error(`Unable to find an available port in range ${startPort}-${MAX_PORT}`)
}

const isPortInUse = (port: number): Promise<boolean> => {
return new Promise((resolve) => {
const server = net.createServer()
server.once('error', () => {
resolve(true)
})
server.once('listening', () => {
server.close()
resolve(false)
})
server.listen(port)
})
}
6 changes: 5 additions & 1 deletion lib/cmd-fns/dev/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { startFsWatcher } from "./start-fs-watcher"
import { uploadExamplesFromDirectory } from "./upload-examples-from-directory"
import posthog from "lib/posthog"
import crypto from 'crypto'
import { findAvailablePort } from "./find-available-port"

export const devCmd = async (ctx: AppContext, args: any) => {
const params = z
Expand All @@ -26,9 +27,12 @@ export const devCmd = async (ctx: AppContext, args: any) => {
})
.parse(args)

const { port } = params
let { port } = params
const { cwd } = ctx

// Find an available port
port = await findAvailablePort(port)

const projectHash = crypto.createHash('md5').update(cwd).digest('hex')

posthog.capture({
Expand Down

0 comments on commit 67e57f5

Please sign in to comment.