@@ -2,7 +2,6 @@ import type { MiddlewareHandler } from 'hono'
22import { ReadStream , createReadStream , existsSync , lstatSync } from 'fs'
33import { getFilePath } from 'hono/utils/filepath'
44import { getMimeType } from 'hono/utils/mime'
5- import { Readable } from 'stream'
65
76export type ServeStaticOptions = {
87 /**
@@ -14,6 +13,24 @@ export type ServeStaticOptions = {
1413 rewriteRequestPath ?: ( path : string ) => string
1514}
1615
16+ const createStreamBody = ( stream : ReadStream ) => {
17+ const body = new ReadableStream ( {
18+ start ( controller ) {
19+ stream . on ( 'data' , ( chunk ) => {
20+ controller . enqueue ( chunk )
21+ } )
22+ stream . on ( 'end' , ( ) => {
23+ controller . close ( )
24+ } )
25+ } ,
26+
27+ cancel ( ) {
28+ stream . destroy ( )
29+ } ,
30+ } )
31+ return body
32+ }
33+
1734export const serveStatic = ( options : ServeStaticOptions = { root : '' } ) : MiddlewareHandler => {
1835 return async ( c , next ) => {
1936 // Do nothing if Response is already set
@@ -52,9 +69,7 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }): Middlew
5269
5370 if ( ! range ) {
5471 c . header ( 'Content-Length' , size . toString ( ) )
55- // Ignore the type mismatch. `c.body` can accept ReadableStream.
56- // @ts -ignore
57- return c . body ( ReadStream . toWeb ( createReadStream ( path ) ) , 200 )
72+ return c . body ( createStreamBody ( createReadStream ( path ) ) , 200 )
5873 }
5974
6075 c . header ( 'Accept-Ranges' , 'bytes' )
@@ -76,7 +91,6 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }): Middlew
7691 c . header ( 'Content-Length' , chunksize . toString ( ) )
7792 c . header ( 'Content-Range' , `bytes ${ start } -${ end } /${ stat . size } ` )
7893
79- // @ts -ignore
80- return c . body ( Readable . toWeb ( stream ) , 206 )
94+ return c . body ( createStreamBody ( stream ) , 206 )
8195 }
8296}
0 commit comments