Skip to content

Commit bc5df03

Browse files
SgtPookimcollina
andauthored
fix: reply.send supports Uint8Array payload (fastify#5124)
* test: false positive Uint8Array view length False positive test proving bug from fastify#5118 * fix(reply.send): support Uint8Array payloads fixes fastify#5118 * Update lib/reply.js Co-authored-by: Matteo Collina <[email protected]> * chore: address PR comments --------- Co-authored-by: Matteo Collina <[email protected]>
1 parent 9b8a782 commit bc5df03

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

lib/reply.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ Reply.prototype.send = function (payload) {
164164
if (hasContentType === false) {
165165
this[kReplyHeaders]['content-type'] = CONTENT_TYPE.OCTET
166166
}
167-
const payloadToSend = Buffer.isBuffer(payload) ? payload : Buffer.from(payload.buffer)
167+
const payloadToSend = Buffer.isBuffer(payload) ? payload : Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength)
168168
onSendHook(this, payloadToSend)
169169
return this
170170
}

test/internals/reply.test.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2148,3 +2148,29 @@ test('reply.send will intercept ERR_HTTP_HEADERS_SENT and log an error message',
21482148
t.equal(err.code, 'ERR_HTTP_HEADERS_SENT')
21492149
}
21502150
})
2151+
2152+
test('Uint8Array view of ArrayBuffer returns correct byteLength', t => {
2153+
t.plan(5)
2154+
const fastify = Fastify()
2155+
2156+
const arrBuf = new ArrayBuffer(100)
2157+
const arrView = new Uint8Array(arrBuf, 0, 10)
2158+
fastify.get('/', function (req, reply) {
2159+
return reply.send(arrView)
2160+
})
2161+
2162+
fastify.listen({ port: 0 }, err => {
2163+
t.error(err)
2164+
t.teardown(fastify.close.bind(fastify))
2165+
2166+
fastify.inject({
2167+
method: 'GET',
2168+
url: '/'
2169+
}, (err, response) => {
2170+
t.error(err)
2171+
t.equal(response.headers['content-type'], 'application/octet-stream')
2172+
t.equal(response.headers['content-length'], '10')
2173+
t.same(response.rawPayload.byteLength, arrView.byteLength)
2174+
})
2175+
})
2176+
})

0 commit comments

Comments
 (0)