How can I store an integer in a nodejs Buffer?

jergason picture jergason · Nov 8, 2011 · Viewed 34.9k times · Source

The nodejs Buffer is pretty swell. However, it seems to be geared towards storing strings. The constructors either take a string, an array of bytes, or a size of bytes to allocate.

I am using version 0.4.12 of Node.js, and I want to store an integer in a buffer. Not integer.toString(), but the actual bytes of the integer. Is there an easy way to do this without looping over the integer and doing some bit-twiddling? I could do that, but I feel like this is a problem someone else must have faced at some time.

Answer

Chris Biscardi picture Chris Biscardi · Nov 8, 2011
var buf = new Buffer(4);
buf.writeUInt8(0x3, 0);

http://nodejs.org/docs/v0.6.0/api/buffers.html#buffer.writeUInt8