From f274a8914659e0b5da5a1324610dc2e8d48dc2e7 Mon Sep 17 00:00:00 2001 From: Divyansh Singh <40380293+brc-dd@users.noreply.github.com> Date: Thu, 30 Jul 2026 03:12:04 +0530 Subject: [PATCH] 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 --- src/node/serve/serve.ts | 38 ++++++++++++++++---------------------- 1 file changed, 16 insertions(+), 22 deletions(-) diff --git a/src/node/serve/serve.ts b/src/node/serve/serve.ts index 3ff1f0ac..7483702b 100644 --- a/src/node/serve/serve.ts +++ b/src/node/serve/serve.ts @@ -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}/`) - }) } + + return polka({ onNoMatch }) + .use(compress, serve) + .listen(port, () => { + config.logger.info(`Built site served at http://localhost:${port}/`) + }) }