0

Is it possible to read buffer line by line in JS?

I currently have a JS buffer object.

If i do console.log(buff) it will print something like this

<Buffer 0c 00 00 00 99 4e 98 3a f0 9d 09 3b 00 00 00 00 68 48 12 3c f0 77 1f 4a 6c 6c 0a 4a 0f 32 5f 31 31 39 38 36 31 5f 31 33 33 39 33 39 40 fc 11 00 09 00 ... 336 more bytes>

I am wondering if there is a way in Javascript to read this like a stream. I know in python for instance I can read the buffer like a stream byte byte.. something like (below)

buff.read(1) 
0c
buff.read(2)
00 00
buff.read(4)
00 99 4e 98
1
  • Why has someone tagged this question for close? Can you clarify? Commented Feb 13, 2020 at 18:14

2 Answers 2

2

I am not sure what your use case is but Buffer implements Uint8Array which effectively makes it iterable. So you can get the values like this

const buffer = Buffer.from("This is string");

for (const b of buffer) {
  console.log(b);
}

You could also consider creating a read function which can do similar thing for you

function read(size) {
  return buffer.slice(0, size);
}

You can use it like this

read(3);

You could also use buffer.keys(), buffer.values() and buffer.entries() to get keys, values and key value respectively using these functions.

Hope this helps.

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

Comments

1

The Buffer documentation shows that Buffer has a subarray method (and also a slice method), either of which can be used directly or to implement a utility method to do this.

Using it directly:

let n = 0;
buff.slice(n, n += 1);
// [0c]
buff.slice(n, n += 2);
// [00, 00]
buff.slice(n, n += 4);
// [00, 99, 4e, 98]

You could encapsulate that into a function if you don't want to keep track of n.

Comments

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.