refactor(serve): simplify static server setup

Read the 404 page with fs/promises, replace the trimChar helper with
a regex, and flatten the if/else around listen.

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

@ -1,22 +1,10 @@
import compression from '@polka/compression'
import fs from 'node:fs'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import polka, { type IOptions } from 'polka'
import sirv from 'sirv'
import { resolveConfig } from '../config'
function trimChar(str: string, char: string) {
while (str.charAt(0) === char) {
str = str.substring(1)
}
while (str.charAt(str.length - 1) === char) {
str = str.substring(0, str.length - 1)
}
return str
}
export interface ServeOptions {
base?: string
root?: string
@ -26,14 +14,20 @@ export interface ServeOptions {
export async function serve(options: ServeOptions = {}) {
const port = options.port ?? 4173
const config = await resolveConfig(options.root, 'serve', 'production')
const base = trimChar(options?.base ?? config?.site?.base ?? '', '/')
const base = (options?.base ?? config?.site?.base ?? '').replace(
/^\/+|\/+$/g,
''
)
const notAnAsset = (pathname: string) =>
!pathname.includes(`/${config.assetsDir}/`)
const notFound = fs.readFileSync(path.resolve(config.outDir, './404.html'))
const notFound = await readFile(
path.resolve(config.outDir, './404.html'),
'utf8'
)
const onNoMatch: IOptions['onNoMatch'] = (req, res) => {
res.statusCode = 404
if (notAnAsset(req.path)) res.write(notFound.toString())
if (notAnAsset(req.path)) res.write(notFound)
res.end()
}
@ -59,11 +53,11 @@ export async function serve(options: ServeOptions = {}) {
`Built site served at http://localhost:${port}/${base}/`
)
})
} else {
}
return polka({ onNoMatch })
.use(compress, serve)
.listen(port, () => {
config.logger.info(`Built site served at http://localhost:${port}/`)
})
}
}

Loading…
Cancel
Save