Add a length value to the beginning of a Buffer

I'm sending a binary value over a socket using node, and would like to send a 4 byte length value in front of the data so the receiver knows how much data to expect.

How can I accomplish this using buffers? I'm using Protobuf for node to first construct a buffer, then I need to append the size to the beginning of the buffer.

To append to the beginning of the current buffer, the easiest way is to make a new Buffer.

var buf = // Protobuf buffer

// Create a 4-byte buffer with the length.
var prefix = new Buffer(4);
prefix.writeUint32LE(buf.length, 0);

// Join them together as a new Buffer.
var data = Buffer.concat([prefix, buf]);