I'm using Buffer
on my node server and Buffer
on my Javacript client.
For the purposes of saving bytes, I'm looking to send my data to the server through websockets as binary as opposed to JSON.
So, if I had the Javascript object of [ 5, false, 55, "asdf" ]
, I'd like to convert that to the buffer on the client right before sending it. Maybe something like this:
object.toBuffer('int16', 'bool', 'int16', 'utf8');
and read it on the server something like this:
var obj = buffer.read('int16', 'bool', 'int16', 'utf8');
I'm looking at current solutions and it looks like I may have to just do a lot of concat
ing, specifying byte offsets/lengths, converting from ints to booleans, etc.
Is there a better way?
Edit: Here's how I think you currently have to do it. I guess my issue is just that it's too verbose and error-prone and I'm looking for a more concise and elegant way to do it, because this operation will be performed in many different places in my code.
// On client for [ 5, false, 55, "test" ]
const writeFirst = Buffer.allocUnsafe(2);
writeFirst.writeInt16LE(5, 0);
const writeSecond = Buffer.allocUnsafe(1);
writeSecond.writeUInt8(0);
const writeThird = Buffer.allocUnsafe(2);
writeThird.writeInt16LE(55, 0);
const writeFourth = Buffer.from('test');
const result = Buffer.concat([writeFirst, writeSecond, writeThird, writeFourth]);
// On server for reading buffer of [ 5, false, 55, "test" ]
const readFirst = result.readInt16LE(0);
const readSecond = Boolean(result.readUInt8(2));
const readThird = result.readInt16LE(3);
const readFourth = result.toString('utf8', 5);
Edit #2: Was googling around and I think I might want something like protocol buffers. I'm not exactly sure what they are yet or if they apply but it looks like you can specify a schema in a file for all your messages and then serialize your JSON objects to that schema and have it return a buffer, which you can then deserialize using the same schema on the client/other server. I'm going to look in to this some more.