5

I have a string that was sent over a network and arrived on my server as a Buffer. It has been formatted to my own custom protocol (in theory, haven't implemented yet). I wanted to use the first n bytes for a string that will identify the protocol.

I have done:

data.toString('utf8');

on the whole buffer but that just gives me the whole packet as a string which is not what I want to achieve.

When the message is recieved, how do I convert a subset of the bytes into a string?

Thanks in advance

  • 1
    This isn't quite what you were asking, so I won't post this as an answer... but in case anyone arrived here (like me) because they googled "nodejs how to read first n bytes of a buffer": A buffer is just a byte array so you can access using simple array notation. `b[0]` is the first byte, represented as an unsigned integer from 0 to 255. – Kip Jul 30 '20 at 14:49

3 Answers3

7

The Buffer.toString() method accepts start and end parameters, which you can use to slice out just the subset you want for your substring. This may, depending on your implementation, be faster than allocation a new intermediary Buffer like you suggested in your answer.

Check out Node's Buffer.toString() method for more information.

Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35
jakemingolla
  • 1,613
  • 1
  • 10
  • 13
  • Oh, I'm so stupid. But I think I'll still use my method because I made a wrapper class for the Buffer class that has methods in it. But thanks, maybe I can make adaptations to that class to use the Buffer.toString method – Samuel Innocent-Primus Mungy Jun 18 '19 at 21:53
3

I know I'm a bit late to this, but why not just something like:

buffer.subarray(0, bytes).toString();
devbanana
  • 466
  • 4
  • 14
2

Found out how.

You have to copy the amount of bytes you want into another buffer by calling the method copy on the original buffer i.e:

sourceBuffer.copy(targetBuffer, targetStartIndex, sourceStartIndex, sourceEndIndex)

This will give your targetBuffer the required data which you can then call toString() or any other metod to convert the buffer array into your desired data type.