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

fix: avoid Readable.toWeb() which causes CI failure #71

Merged
merged 1 commit into from
Jul 16, 2023
Merged
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
26 changes: 20 additions & 6 deletions src/serve-static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import type { MiddlewareHandler } from 'hono'
import { ReadStream, createReadStream, existsSync, lstatSync } from 'fs'
import { getFilePath } from 'hono/utils/filepath'
import { getMimeType } from 'hono/utils/mime'
import { Readable } from 'stream'

export type ServeStaticOptions = {
/**
Expand All @@ -14,6 +13,24 @@ export type ServeStaticOptions = {
rewriteRequestPath?: (path: string) => string
}

const createStreamBody = (stream: ReadStream) => {
const body = new ReadableStream({
start(controller) {
stream.on('data', (chunk) => {
controller.enqueue(chunk)
})
stream.on('end', () => {
controller.close()
})
},

cancel() {
stream.destroy()
},
})
return body
}

export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {
return async (c, next) => {
// Do nothing if Response is already set
Expand Down Expand Up @@ -52,9 +69,7 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }): Middlew

if (!range) {
c.header('Content-Length', size.toString())
// Ignore the type mismatch. `c.body` can accept ReadableStream.
// @ts-ignore
return c.body(ReadStream.toWeb(createReadStream(path)), 200)
return c.body(createStreamBody(createReadStream(path)), 200)
}

c.header('Accept-Ranges', 'bytes')
Expand All @@ -76,7 +91,6 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }): Middlew
c.header('Content-Length', chunksize.toString())
c.header('Content-Range', `bytes ${start}-${end}/${stat.size}`)

// @ts-ignore
return c.body(Readable.toWeb(stream), 206)
return c.body(createStreamBody(stream), 206)
}
}