0

So I have .bin file and I want to read it. I tried using .readFileSync("file.bin"), but I get strange console.log (when I try to log certain element) as I understand I get bytes.

Can someone tell me how do I get these values in array for example:

 04 40 10 01 0a 1a 10 02 10 03 0d 02 0d 03 05 03 05 03 05 03 05 03 0f 32 0e 12 11 02 07 e6 0b 00

Code:

const fs = require('fs'); //file sysyem = fs
const decryptor  = fs.readFileSync('./docs/decryptor.bin');
console.log(decryptor)

console.log(decryptor[0])

So the first log I get is :

<Buffer 04 40 10 01 0a 1a 10 02 10 03 0d 02 0d 03 05 03 05 03 05 03 05 03 0f 32 0e 12 11 02 07 e6 0b 00>

And for second one I get:

4
gfiselv
  • 27
  • 5
  • Can you elaborate about why you think that is strange? (it's working as expected.) What were you expecting? – Wyck Dec 09 '20 at 18:23
  • Okay, not strange. How can I get values I mentioned before into array for example? – gfiselv Dec 09 '20 at 18:25
  • That'd be a duplicate question: https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer – Wyck Dec 09 '20 at 18:25
  • Also documented well here: https://nodejs.org/api/buffer.html#buffer_buffers_and_typedarrays – Wyck Dec 09 '20 at 18:27
  • So, you have a Buffer and you can access it like an array. What exactly are you trying to do with this data? I'm wondering if you can just accomplish that by directly accessing the data in the Buffer using array-like syntax. – jfriend00 Dec 09 '20 at 18:50

1 Answers1

1

Let's unpack this. Pun intended.

.readFileSync(), the way you use it, returns a Buffer object with one element for each byte in your file. That's what you see from console.log(decryptor), the entire buffer. console.log renders the contents of buffers in hexidecimal. That is, the decimal value 4 is rendered 04, and the decimal value 10 is rendered 0a. Keep in mind that it's console.log doing the <Buffer 04 40 10 01 0a 1a ... display.

Then, when you do let v = decryptor[0] you take the first element of that buffer and assign it to v. That's a plain old number, in your case 4. So, console.log(decryptor[0]) shows up as just 4.

A little more detail for you: nodejs Buffers are instances of Uint8Arrays: arrays of unsigned 8-bit numbers. That's why you get numbers from your decryptor[0] and other element lookups. Read this. Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

O. Jones
  • 81,279
  • 15
  • 96
  • 133