From 5573c59cf6d047a5bf3feed371ee261c9571aaf6 Mon Sep 17 00:00:00 2001 From: Yusuke Wada Date: Mon, 19 Sep 2022 12:25:04 +0900 Subject: [PATCH] fix(bun): serve static middleware returns 404 correctly (#538) --- bun_test/index.test.tsx | 5 +++++ src/middleware/serve-static/bun.ts | 26 ++++++++++++++------------ 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/bun_test/index.test.tsx b/bun_test/index.test.tsx index 7962cbca..9da021e1 100644 --- a/bun_test/index.test.tsx +++ b/bun_test/index.test.tsx @@ -67,6 +67,11 @@ describe('Serve Static Middleware', () => { expect(res.status).toBe(200) expect(res.headers.get('Content-Type')).toBe('image/x-icon') }) + + it('Should return 404 response', async () => { + const res = await app.request(new Request('http://localhost/favicon-notfound.ico')) + expect(res.status).toBe(404) + }) }) // JWT is not available for Bun diff --git a/src/middleware/serve-static/bun.ts b/src/middleware/serve-static/bun.ts index d8c5928e..a2d76eab 100644 --- a/src/middleware/serve-static/bun.ts +++ b/src/middleware/serve-static/bun.ts @@ -1,5 +1,6 @@ // @denoify-ignore /* eslint-disable @typescript-eslint/ban-ts-comment */ +import { existsSync } from 'fs' import type { MiddlewareHandler } from '../../hono' import { getFilePath } from '../../utils/filepath' import { getMimeType } from '../../utils/mime' @@ -20,7 +21,6 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }): Middlew if (c.res && c.finalized) { await next() } - const url = new URL(c.req.url) let path = getFilePath({ @@ -28,20 +28,22 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }): Middlew root: options.root, defaultDocument: DEFAULT_DOCUMENT, }) - path = `./${path}` - const content = file(path) - if (content) { - const mimeType = getMimeType(path) - if (mimeType) { - c.header('Content-Type', mimeType) + + if (existsSync(path)) { + const content = file(path) + if (content) { + const mimeType = getMimeType(path) + if (mimeType) { + c.header('Content-Type', mimeType) + } + // Return Response object + return c.body(content) } - // Return Response object - return c.body(content) - } else { - console.warn(`Static file: ${path} is not found`) - await next() } + + console.warn(`Static file: ${path} is not found`) + await next() return } }