fix: ServeStatic content-length transfer-encoding

both headers cannot co-exist at the same time, so we pass the expected
content-length value into 2nd param of Response.stream(), so that the
internal can decide to add it only when required
This commit is contained in:
Bobby Wibowo 2022-07-29 10:16:49 +07:00
parent 8748dcefb0
commit 681a3ca32f
No known key found for this signature in database
GPG Key ID: 51C3A1E1E22D26CF

View File

@ -226,15 +226,14 @@ class ServeStatic {
opts.start = offset opts.start = offset
opts.end = Math.max(offset, offset + len - 1) opts.end = Math.max(offset, offset + len - 1)
// content-length
res.header('Content-Length', String(len))
// HEAD support // HEAD support
if (req.method === 'HEAD') { if (req.method === 'HEAD') {
// If HEAD, also set Content-Length (must be string)
res.header('Content-Length', String(len))
return res.end() return res.end()
} }
return this.#stream(req, res, fullPath, opts) return this.#stream(req, res, fullPath, opts, len)
} }
async #setHeaders (req, res, stat) { async #setHeaders (req, res, stat) {
@ -264,7 +263,7 @@ class ServeStatic {
} }
} }
async #stream (req, res, fullPath, opts) { async #stream (req, res, fullPath, opts, len) {
const readStream = fs.createReadStream(fullPath, opts) const readStream = fs.createReadStream(fullPath, opts)
readStream.on('error', error => { readStream.on('error', error => {
@ -272,7 +271,8 @@ class ServeStatic {
logger.error(error) logger.error(error)
}) })
return res.stream(readStream) // 2nd param will be set as Content-Length header (must be number)
return res.stream(readStream, len)
} }
get handler () { get handler () {