Skip to content

Commit

Permalink
fix: avoid Readable.toWeb() which causes CI failure (#71)
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe committed Jul 16, 2023
1 parent 2dfd8f0 commit 5064e92
Showing 1 changed file with 20 additions and 6 deletions.
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)
}
}

0 comments on commit 5064e92

Please sign in to comment.