Skip to content

Commit

Permalink
feat(serve-static): introduce onNotFound option (#119)
Browse files Browse the repository at this point in the history
* feat(serve-static): introduce `onNotFound` option

* tweak
  • Loading branch information
yusukebe authored Jan 1, 2024
1 parent 8761cac commit 8a70dce
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,22 @@ app.use(
)
```

#### `onNotFound`

The `onNotFound` is useful for debugging. You can write a handle for when a file is not found.

```ts
app.use(
'/static/*',
serveStatic({
root: './non-existent-dir',
onNotFound: (path, c) => {
console.log(`${path} is not found, request to ${c.req.path}`)
},
})
)
```

## Related projects

- Hono - <https://hono.dev>
Expand Down
6 changes: 4 additions & 2 deletions src/serve-static.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { ReadStream} from 'fs'
import type { ReadStream } from 'fs'
import { createReadStream, existsSync, lstatSync } from 'fs'
import type { MiddlewareHandler } from 'hono'
import type { Context, MiddlewareHandler } from 'hono'
import { getFilePath } from 'hono/utils/filepath'
import { getMimeType } from 'hono/utils/mime'

Expand All @@ -12,6 +12,7 @@ export type ServeStaticOptions = {
path?: string
index?: string // default is 'index.html'
rewriteRequestPath?: (path: string) => string
onNotFound?: (path: string, c: Context) => void | Promise<void>
}

const createStreamBody = (stream: ReadStream) => {
Expand Down Expand Up @@ -51,6 +52,7 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }): Middlew
path = `./${path}`

if (!existsSync(path)) {
await options.onNotFound?.(path, c)
return next()
}

Expand Down
19 changes: 19 additions & 0 deletions test/serve-static.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@ describe('Serve Static Middleware', () => {
})
)

let notFoundMessage = ''
app.use(
'/on-not-found/*',
serveStatic({
root: './not-found',
onNotFound: (path, c) => {
notFoundMessage = `${path} is not found, request to ${c.req.path}`
},
})
)

const server = createAdaptorServer(app)

it('Should return index.html', async () => {
Expand Down Expand Up @@ -110,4 +121,12 @@ describe('Serve Static Middleware', () => {
expect(res.text.length).toBe(17)
expect(res.text).toBe('This is plain.txt')
})

it('Should handle the `onNotFound` option', async () => {
const res = await request(server).get('/on-not-found/foo.txt')
expect(res.status).toBe(404)
expect(notFoundMessage).toBe(
'./not-found/on-not-found/foo.txt is not found, request to /on-not-found/foo.txt'
)
})
})

0 comments on commit 8a70dce

Please sign in to comment.