I was trying to split a typedArray into smaller chunks, with this simple code snippet:
const buf = new Uint8Array([0x02, 0x00, 0x07, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x00, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x61, 0x70, 0x70, 0x02])
const len = 5
for (let i=0; i<buf.length;){
const chunk = buf.slice(i, len)
console.log("Chunk", chunk, "from", i, "to", i + chunk.length)
if (chunk.length) {
i += chunk.length
} else {
console.log("Chunk is empty")
break
}
}
But what I found is that slice
only works the first iteration, returning empty chunks the next ones.
I noticed that it also happens in Node.js, if I replace the first line with:
const buf = Buffer.from([0x02, 0x00, 0x07, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x00, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x61, 0x70, 0x70, 0x02])
Why this behaviour?
via dysfuntcional
No comments:
Post a Comment