Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(serve-static): support absolute path for root #202

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ import { serveStatic } from '@hono/node-server/serve-static'
app.use('/static/*', serveStatic({ root: './' }))
```

Note that `root` must be _relative_ to the current working directory from which the app was started. Absolute paths are not supported.
Note that `root` must be _relative_ to the current working directory from which the app was started.

This can cause confusion when running your application locally.

Expand Down
24 changes: 18 additions & 6 deletions src/serve-static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ const createStreamBody = (stream: ReadStream) => {
return body
}

const addCurrentDirPrefix = (path: string) => {
return `./${path}`
const addDirPrefix = (path: string, absolute: boolean) => {
return absolute ? '/' + path : `./${path}`
}

const getStats = (path: string) => {
Expand All @@ -57,6 +57,18 @@ const getStats = (path: string) => {
}

export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {
let isAbsoluteRoot = false
let root: string

if (options.root) {
if (options.root.startsWith('/')) {
isAbsoluteRoot = true
root = new URL(`file://${options.root}`).pathname
} else {
root = options.root
}
}

return async (c, next) => {
// Do nothing if Response is already set
if (c.finalized) {
Expand All @@ -67,11 +79,11 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }): Middlew

let path = getFilePathWithoutDefaultDocument({
filename: options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename,
root: options.root,
root,
})

if (path) {
path = addCurrentDirPrefix(path)
path = addDirPrefix(path, isAbsoluteRoot)
} else {
return next()
}
Expand All @@ -81,12 +93,12 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }): Middlew
if (stats && stats.isDirectory()) {
path = getFilePath({
filename: options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename,
root: options.root,
root,
defaultDocument: options.index ?? 'index.html',
})

if (path) {
path = addCurrentDirPrefix(path)
path = addDirPrefix(path, isAbsoluteRoot)
} else {
return next()
}
Expand Down
1 change: 1 addition & 0 deletions test/assets/static-absolute-root-with-dots/hello.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello with absolute root with dots
1 change: 1 addition & 0 deletions test/assets/static-absolute-root/hello.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello with absolute root
27 changes: 27 additions & 0 deletions test/serve-static.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Hono } from 'hono'
import request from 'supertest'
import path from 'path'
import { serveStatic } from './../src/serve-static'
import { createAdaptorServer } from './../src/server'

Expand Down Expand Up @@ -43,6 +44,16 @@ describe('Serve Static Middleware', () => {
})
)

app.all(
'/static-absolute-root/*',
serveStatic({ root: path.join(path.dirname(__filename), 'assets') })
)

app.all(
'/static-absolute-root-with-dots/*',
serveStatic({ root: path.join(path.dirname(__filename), 'assets') + '/../assets' })
)

const server = createAdaptorServer(app)

it('Should return index.html', async () => {
Expand Down Expand Up @@ -196,4 +207,20 @@ describe('Serve Static Middleware', () => {
expect(res.headers['vary']).toBeUndefined()
expect(res.text).toBe('Hello Not Compressed')
})

it('Should return 200 with an absolute root - /static-absolute-root/hello.txt', async () => {
const res = await request(server).get('/static-absolute-root/hello.txt')
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('text/plain; charset=utf-8')
expect(res.headers['content-length']).toBe('24')
expect(res.text).toBe('Hello with absolute root')
})

it('Should return 200 with an absolute root with dots - /static-absolute-root-with-dots/hello.txt', async () => {
const res = await request(server).get('/static-absolute-root-with-dots/hello.txt')
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('text/plain; charset=utf-8')
expect(res.headers['content-length']).toBe('34')
expect(res.text).toBe('Hello with absolute root with dots')
})
})