0

Beginner trying to work with Bytes using Node.js. I use this Buffer

This line:

let a = new Uint8Array([64, 9, 33, 251, 84, 65, 23, 68, 1, 2, 3]);
console.log(a.slice(0, 8).buffer);
let x = new DataView(a.slice(0, 8).buffer);
console.log(x.getFloat64(0));

will print as it should be:

ArrayBuffer {
  [Uint8Contents]: <40 09 21 fb 54 41 17 44>,
  byteLength: 8
}
3.1415926535

---

However, this slice().buffer will return 8192 bytes even though input is the same 10 bytes:

let b = Buffer.from([64, 9, 33, 251, 84, 65, 23, 68, 1, 2, 3]);
console.log("b only = ", b);
console.log("b buff = ", b.slice(0, 8).buffer);
let y = new DataView(b.slice(0, 8).buffer);
console.log(y.getFloat64(0));

print:

b only =  <Buffer 40 09 21 fb 54 41 17 44 01 02 03>
b buff =  ArrayBuffer {
  [Uint8Contents]: <64 65 63 6c 61 72 65 20 6d 6f 64 75 6c 65 20 22 61 73 73 65 72 74 22 20 7b 0a 20 20 20 20 66 75 6e 63 74 69 6f 6e 20 61 73 73 65 72 74 28 76 61 6c 75 65 3a 20 61 6e 79 2c 20 6d 65 73 73 61 67 65 3f 3a 20 73 74 72 69 6e 67 20 7c 20 45 72 72 6f 72 29 3a 20 61 73 73 65 72 74 73 20 76 61 6c 75 65 3b 0a ... 8092 more bytes>,
  byteLength: 8192
}
4.2319958073098126e+175

---

b.slice() here will still return the full-underlying-memory.

let c = Buffer.alloc(12).fill(b.slice(0,8));
console.log(c.buffer);
let z = new DataView(c.buffer);
console.log(z.getFloat64(0));

print:

ArrayBuffer {
  [Uint8Contents]: <40 09 21 fb 54 41 17 44 40 09 21 fb>,
  byteLength: 12
}
3.1415926535

---

My questions are:

  1. Why does Buffer.from(number[]).buffer produce 8192 bytes?
  2. How to get the correct ArrayBuffer from Buffer.slice object without creating new var and alloc(size)?
nyoto arif
  • 55
  • 8
  • alright so i got the answer for (2) from this [link](https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer). ZachB answer gave example to use `b.buffer.slice()`, which give the correct ArrayBuffer object as what i wanted. – nyoto arif Jun 19 '20 at 12:32

0 Answers0