Skip to content

Commit

Permalink
feat: auto increment for ports
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Apr 29, 2021
1 parent a0aa67a commit 9ef11bb
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions packages/slidev/node/cli.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import path from 'path'
import http from 'http'
import fs from 'fs-extra'
import yargs, { Argv } from 'yargs'
import prompts from 'prompts'
Expand All @@ -24,7 +25,6 @@ cli.command(
args => commonOptions(args)
.option('port', {
alias: 'p',
default: 3030,
type: 'number',
describe: 'port',
})
Expand Down Expand Up @@ -64,6 +64,7 @@ cli.command(
if (server)
await server.close()
const options = await resolveOptions({ entry, theme }, 'dev')
port = port || await findFreePort(3030)
server = (await createServer(
options,
{
Expand Down Expand Up @@ -184,7 +185,7 @@ cli.command(
output = output || `${path.basename(entry, '.md')}-export`
process.env.NODE_ENV = 'production'
const { exportSlides } = await import('./export')
const port = 12445
const port = await findFreePort(12445)
const options = await resolveOptions({ entry, theme }, 'build')
const server = await createServer(
options,
Expand All @@ -195,7 +196,7 @@ cli.command(
clearScreen: false,
},
)
await server.listen()
await server.listen(port)
printInfo(options)
parser.filterDisabled(options.data)
output = await exportSlides({
Expand Down Expand Up @@ -244,3 +245,22 @@ function printInfo(options: ResolvedSlidevOptions, port?: number) {
console.log()
console.log()
}

function isPortFree(port: number) {
return new Promise((resolve) => {
const server = http.createServer()
.listen(port, () => {
server.close()
resolve(true)
})
.on('error', () => {
resolve(false)
})
})
}

async function findFreePort(start: number): Promise<number> {
if (await isPortFree(start))
return start
return findFreePort(start + 1)
}

0 comments on commit 9ef11bb

Please sign in to comment.