Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/serve-static.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Context, Env, MiddlewareHandler } from 'hono'
import { getMimeType } from 'hono/utils/mime'
import type { ReadStream, Stats } from 'node:fs'
import { createReadStream, lstatSync } from 'node:fs'
import { createReadStream, lstatSync, existsSync } from 'node:fs'
import { join } from 'node:path'

export type ServeStaticOptions<E extends Env = Env> = {
Expand Down Expand Up @@ -59,6 +59,10 @@ export const serveStatic = <E extends Env = any>(
const root = options.root || ''
const optionPath = options.path

if (root !== '' && !existsSync(root)) {
console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`)
}

return async (c, next) => {
// Do nothing if Response is already set
if (c.finalized) {
Expand Down
24 changes: 24 additions & 0 deletions test/serve-static.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,3 +325,27 @@ describe('Serve Static Middleware', () => {
})
})
})

describe('Serve Static Middleware with wrong path', () => {
it('Should show an error when the path is wrong', async () => {
const logSpy = jest.spyOn(console, 'error')

const app = new Hono<{
Variables: {
path: string
}
}>()

app.use(
'*',
serveStatic({
root: './public',
})
)

expect(logSpy).toHaveBeenCalledWith(
// eslint-disable-next-line quotes
"serveStatic: root path './public' is not found, are you sure it's correct?"
)
})
})
Loading