Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs add null terminated string to buffer

Tags:

node.js

I am trying to replicate a packet.

This packet:

2C 00 65 00 03 00 00 00   00 00 00 00 42 4C 41 5A
45 00 00 00 00 00 00 00   00 42 4C 41 5A 45......

2c 00 is the size of the packet...
65 00 is the packet id 101...
03 00 is the number of elements in the array...

Now here comes my problem, 42 4C 41 5A 45 is a string... There are exactly 3 Instances of that string in that packet if it is complete... But my problem is it is not just null terminated it has 00 00 00 00 spaces between those instances.

My code:

function channel_list(channels) {
  var packet = new SmartBuffer();

  packet.writeUInt16LE(101); // response packet for list of channels
  packet.writeUInt16LE(channels.length)

  channels.forEach(function (key){
    console.log(key);
    packet.writeStringNT(key);
  });

  packet.writeUInt16LE(packet.length + 2, 0);

  console.log(packet.toBuffer());
}

But how do I add the padding?

I am using this package, https://github.com/JoshGlazebrook/smart-buffer/

like image 984
majidarif Avatar asked Feb 04 '26 09:02

majidarif


1 Answers

Smart-Buffer keeps track of its position for you so you do not need to specify an offset to know where to insert the data to pad your string. You could do something like this with your existing code:

channels.forEach(function (key){
    console.log(key);
    packet.writeString(key);   // This is the string with no padding added.
    packet.writeUInt32BE(0);   // Four 0x00's are added after the string itself.
});

I'm assuming you want: 42 4C 41 5A 45 00 00 00 00 42 4C 41 5A 45 00 00 00 00 etc.

Editing based on comments:

There is no built in way to do what you want, but you could do something like this:

channels.forEach(function (key){
    console.log(key);
    packet.writeString(key); 
    for(var i = 0; i <= (9 - key.length); i++)
        packet.writeInt8(0);
});
like image 163
Josh Avatar answered Feb 06 '26 22:02

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!