From 5064e925e78ab0dee1d5e8b10cc63f9b1c5929cf Mon Sep 17 00:00:00 2001 From: Yusuke Wada Date: Sun, 16 Jul 2023 16:22:43 +0900 Subject: [PATCH] fix: avoid `Readable.toWeb()` which causes CI failure (#71) --- src/serve-static.ts | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/src/serve-static.ts b/src/serve-static.ts index 45e0b9f..22308f8 100644 --- a/src/serve-static.ts +++ b/src/serve-static.ts @@ -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 = { /** @@ -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 @@ -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') @@ -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) } }