Skip to content

feat: add sendFile helper to serve a dynamically chosen file - #395

Open
SynthLuvr wants to merge 2 commits into
honojs:mainfrom
SynthLuvr:feat/send-file
Open

feat: add sendFile helper to serve a dynamically chosen file#395
SynthLuvr wants to merge 2 commits into
honojs:mainfrom
SynthLuvr:feat/send-file

Conversation

@SynthLuvr

Copy link
Copy Markdown

Fixes #205

Adds a sendFile(c, path, options) helper, importable from @hono/node-server/send-file, that serves the file at a given path with the same behavior and features as the serveStatic middleware (MIME types, streaming, HEAD/OPTIONS, range requests, precompressed files, root/index/onFound options). This enables serving a file whose path is determined dynamically, like res.sendFile() of Express, and solves the use case of honojs/hono#4012 without requiring any changes to the core: sendFile always returns a Response, so it satisfies the current handler types.

The file serving logic is shared between serveStatic and sendFile by extracting it into internal findFile/serveFile helpers, without changing the behavior of serveStatic.

The author should do the following, if applicable

  • Add tests
  • Run tests
  • pnpm run format:fix && pnpm run lint:fix to format the code
  • Add TSDoc/JSDoc to document the code

Fixes honojs#205

Adds a `sendFile(c, path, options)` helper, importable from
`@hono/node-server/send-file`, that serves the file at a given path with
the same behavior and features as the `serveStatic` middleware (MIME
types, streaming, HEAD/OPTIONS, range requests, precompressed files,
`root`/`index`/`onFound` options). This enables serving a file whose
path is determined dynamically, like `res.sendFile()` of Express, and
solves the use case of honojs/hono#4012 without requiring any changes to
the core: `sendFile` always returns a `Response`, so it satisfies the
current handler types.

The file serving logic is shared between `serveStatic` and `sendFile`
by extracting it into internal `findFile`/`serveFile` helpers, without
changing the behavior of `serveStatic`.
- Derive SendFileOptions from ServeStaticOptions via Pick instead of
  duplicating the shared option fields
- Split serveFile into findPrecompressedFile, createFileResponse and
  createRangeResponse so each unit is small and flat
- Rewrite findFile with an early return instead of mutating locals
- Drop comments that restate the code or reference serveStatic from
  shared code; keep the ones explaining non-obvious behavior
- Fix a duplicated and misleading test name in send-file tests
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request] Support sendFile

1 participant