title: How to convert a Javascript Object to a Node Buffer?
body: <p>I'm using <code>Buffer</code> on my node server and <a href="https://github.com/feross/buffer" rel="noreferrer"><code>Buffer</code></a> on my Javacript client.</p>
  
  <p>For the purposes of saving bytes, I'm looking to send my data to the server through websockets as binary as opposed to JSON.</p>
  
  <p>So, if I had the Javascript object of <code>[ 5, false, 55, "asdf" ]</code>, I'd like to convert that to the buffer on the client right before sending it. Maybe something like this:</p>
  
  <pre><code>object.toBuffer('int16', 'bool', 'int16', 'utf8');
  </code></pre>
  
  <p>and read it on the server something like this:</p>
  
  <pre><code>var obj = buffer.read('int16', 'bool', 'int16', 'utf8');
  </code></pre>
  
  <p>I'm looking at current solutions and it looks like I may have to just do a lot of <code>concat</code>ing, specifying byte offsets/lengths, converting from ints to booleans, etc.</p>
  
  <p>Is there a better way?</p>
  
  <p><strong>Edit:</strong> 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.</p>
  
  <pre><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);
  </code></pre>
  
  <p><strong>Edit #2:</strong> 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.</p>