Skip to content

Commit fa9fd90

Browse files
authored
fix(File): respect typed array byteOffset and byteLength (#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.
1 parent ae6f554 commit fa9fd90

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

lib/fetch/file.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,9 @@ function processBlobParts (parts, options) {
278278
if (!element.buffer) { // ArrayBuffer
279279
bytes.push(new Uint8Array(element))
280280
} else {
281-
bytes.push(element.buffer)
281+
bytes.push(
282+
new Uint8Array(element.buffer, element.byteOffset, element.byteLength)
283+
)
282284
}
283285
} else if (isBlobLike(element)) {
284286
// 3. If element is a Blob, append the bytes it represents

test/fetch/file.js

+19
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,16 @@ test('File.prototype.text', async (t) => {
120120
t.equal(await file.text(), 'hello world')
121121
t.end()
122122
})
123+
124+
t.test('With TypedArray range', async (t) => {
125+
const uint8_1 = new Uint8Array(Buffer.from('hello world'))
126+
const uint8_2 = new Uint8Array(uint8_1.buffer, 1, 4)
127+
128+
const file = new File([uint8_2], 'hello_world.txt')
129+
130+
t.equal(await file.text(), 'ello')
131+
t.end()
132+
})
123133
/* eslint-enable camelcase */
124134

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

153+
t.test('With Buffer', async (t) => {
154+
const buffer = Buffer.from('hello world')
155+
156+
const file = new File([buffer], 'hello_world.txt')
157+
158+
t.equal(await file.text(), 'hello world')
159+
t.end()
160+
})
161+
143162
t.test('Mixed', async (t) => {
144163
const blob = new Blob(['Hello, '])
145164
const uint8 = new Uint8Array(Buffer.from('world! This'))

0 commit comments

Comments
 (0)