0

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?

2
  • You probably need Array and Dataview. Commented Mar 12, 2018 at 14:28
  • To add more context, you should also specify the type of string to be ascii in your case var firstBuffer = Buffer.from('hello world','ascii'); Commented Mar 12, 2018 at 14:39

1 Answer 1

0

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"

Sign up to request clarification or add additional context in comments.

2 Comments

This is not a view. This is a copy. I guess it suits your need but it is not the answer for people looking for buffer view creation.
The property name is byteOffset. And it is documented (now), though at a trivial place...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.