refactor(serve): resolve once the server is listening

Collapse the duplicated listen branches and await the listening
event; serve() now also rejects on listen errors like EADDRINUSE
instead of crashing in the callback.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
pull/5342/head
Divyansh Singh 1 month ago
parent f97605ff26
commit e40ae7888a

@ -1,4 +1,5 @@
import compression from '@polka/compression'
import { once } from 'node:events'
import path from 'node:path'
import polka, { type IOptions } from 'polka'
import sirv from 'sirv'
@ -42,19 +43,15 @@ export async function serve(options: ServeOptions = {}) {
}
})
if (base) {
return polka({ onNoMatch })
.use(base, compress, serve)
.listen(port, () => {
const app = base
? polka({ onNoMatch }).use(base, compress, serve)
: polka({ onNoMatch }).use(compress, serve)
app.listen(port)
await once(app.server, 'listening')
config.logger.info(
`Built site served at http://localhost:${port}/${base}/`
`Built site served at http://localhost:${port}/${base ? `${base}/` : ''}`
)
})
}
return polka({ onNoMatch })
.use(compress, serve)
.listen(port, () => {
config.logger.info(`Built site served at http://localhost:${port}/`)
})
return app
}

Loading…
Cancel
Save