Skip to content

Commit

Permalink
fix(File): respect typed array byteOffset and byteLength (nodejs#…
Browse files Browse the repository at this point in the history
…1601)

`File` ignored the `byteOffset` and `byteLength` properties of typed
arrays, meaning the entire backing `ArrayBuffer` was included.
Notably, this caused issues when passing `Buffer`s to the `File`
constructor.
  • Loading branch information
mrbbot authored and crysmags committed Feb 27, 2024
1 parent d48369f commit 323f326
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/fetch/file.js
Expand Up @@ -278,7 +278,9 @@ function processBlobParts (parts, options) {
if (!element.buffer) { // ArrayBuffer
bytes.push(new Uint8Array(element))
} else {
bytes.push(element.buffer)
bytes.push(
new Uint8Array(element.buffer, element.byteOffset, element.byteLength)
)
}
} else if (isBlobLike(element)) {
// 3. If element is a Blob, append the bytes it represents
Expand Down
19 changes: 19 additions & 0 deletions test/fetch/file.js
Expand Up @@ -120,6 +120,16 @@ test('File.prototype.text', async (t) => {
t.equal(await file.text(), 'hello world')
t.end()
})

t.test('With TypedArray range', async (t) => {
const uint8_1 = new Uint8Array(Buffer.from('hello world'))
const uint8_2 = new Uint8Array(uint8_1.buffer, 1, 4)

const file = new File([uint8_2], 'hello_world.txt')

t.equal(await file.text(), 'ello')
t.end()
})
/* eslint-enable camelcase */

t.test('With ArrayBuffer', async (t) => {
Expand All @@ -140,6 +150,15 @@ test('File.prototype.text', async (t) => {
t.end()
})

t.test('With Buffer', async (t) => {
const buffer = Buffer.from('hello world')

const file = new File([buffer], 'hello_world.txt')

t.equal(await file.text(), 'hello world')
t.end()
})

t.test('Mixed', async (t) => {
const blob = new Blob(['Hello, '])
const uint8 = new Uint8Array(Buffer.from('world! This'))
Expand Down

0 comments on commit 323f326

Please sign in to comment.