noel
noel

Reputation: 2339

Node Buffer to javascript array with offset

I'm trying to convert a node Buffer to a Uint8ClampedArray, but I want to discard the first 8 bytes. I tried like this:

buf = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
arr = new Uint8ClampedArray(buf, 8, 8);

But it appears as though the offset is ignored, arr contains all of buf.

How can I convert buf to an array beginning at an offset of n bytes?

Upvotes: 1

Views: 458

Answers (1)

André Kugland
André Kugland

Reputation: 915

Just use Buffer.slice:

> arr = new Uint8ClampedArray(buf.slice(8));
Uint8ClampedArray [ 9, 10, 11, 12, 13, 14, 15, 16 ]

By the way, constructing your Buffer this way is deprecated:

> buf = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
<Buffer 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10>
[DEP0005] DeprecationWarning: Buffer() is deprecated due to security and 
usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or 
Buffer.from() methods instead.

Upvotes: 1

Related Questions