Skip to content

Commit 0b1229e

Browse files
authored
fix(serve-static): Use Readable.toWeb in serveStatic (#293)
The previous createStreamBody implementation used flowing mode. This caused a flaw where data would accumulate in the queue if the transmission speed was slower than the read speed, potentially consumig memory equal to the file size. However, as noted in the commit 5064e92 that introduced this issue, using Readable.toWeb may cause an exception in Node.js versions that do not have nodejs/node#54206 applied. Therefore, the old implementation remains. It is desirable that it will be removed when support for older versions of Node.js ends.
1 parent 76d80e6 commit 0b1229e

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

src/serve-static.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { getMimeType } from 'hono/utils/mime'
33
import type { ReadStream, Stats } from 'node:fs'
44
import { createReadStream, statSync, existsSync } from 'node:fs'
55
import { join } from 'node:path'
6+
import { versions } from 'node:process'
7+
import { Readable } from 'node:stream'
68

79
export type ServeStaticOptions<E extends Env = Env> = {
810
/**
@@ -26,7 +28,18 @@ const ENCODINGS = {
2628
} as const
2729
const ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS) as (keyof typeof ENCODINGS)[]
2830

31+
// In Node.js versions that do not have the following PR applied, using Readable.toWeb may cause unexpected exceptions.
32+
// https://github.com/nodejs/node/pull/54206
33+
const pr54206Applied = () => {
34+
const [major, minor] = versions.node.split('.').map((component) => parseInt(component))
35+
return major >= 23 || (major === 22 && minor >= 7) || (major === 20 && minor >= 18)
36+
}
37+
const useReadableToWeb = pr54206Applied()
38+
2939
const createStreamBody = (stream: ReadStream) => {
40+
if (useReadableToWeb) {
41+
return Readable.toWeb(stream) as ReadableStream
42+
}
3043
const body = new ReadableStream({
3144
start(controller) {
3245
stream.on('data', (chunk) => {

0 commit comments

Comments
 (0)