Reputation: 203
I want to create view of part of a buffer, after checking in node.js documentation I found that method Buffer.from(arrayBuffer[, byteOffset[, length]])
should do exactly what I wanted. I started with the simple case but it already produces unexpected results so I'm definitely doing something wrong
var firstBuffer = Buffer.from('hello world');
var secondBuffer = Buffer.from(firstBuffer.buffer, 0, firstBuffer.length);
assert (firstBuffer.0 == secondBuffer.0) // fails
console.log (firstBuffer) // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
console.log (secondBuffer) // <Buffer da 07 00 00 da 07 00 00 db 07 00>
How to create buffer view?
Upvotes: 0
Views: 254
Reputation: 203
It turns out that result of Buffer.from(string)
can have offset
property different than 0
Knowing that modified code works:
var firstBuffer = Buffer.from('hello world');
var secondBuffer = Buffer.from(firstBuffer.buffer, firstBuffer.offset, firstBuffer.length);
console.log (firstBuffer) // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
console.log (secondBuffer) // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
assert (firstBuffer[0] == secondBuffer[0]) // pass
But it a shame that in official documentation there was no info about this "feature"
Upvotes: 0