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

Loading…
Cancel
Save