WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
21 changes: 21 additions & 0 deletions test/serve-static.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,3 +325,24 @@ 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("serveStatic: root path './public' is not found, are you sure it's correct?")
})
})
Loading