Full answer
Binary protocols (file headers, network packets, database drivers) pack numbers into exact byte positions. Buffer offers methods for each size: writeUInt8, writeUInt16BE, writeUInt32LE, writeInt32BE, writeFloatLE, writeDoubleBE and writeBigUInt64BE, with matching read methods.
Endianness is the order of bytes inside a number. Big-endian (BE) puts the most significant byte first, as network protocols do. Little-endian (LE) puts it last, as most CPUs do. The two sides must agree. For a value 0x0102, BE gives bytes 01 02 and LE gives 02 01.
A typical packet design: a magic number, a version byte, a length field, then the payload. The reader checks the magic, reads the length, and waits until it has that many bytes. With streams, one packet may arrive in two chunks, or two packets in one chunk, so the reader must keep a leftover buffer.
Text has a similar problem. UTF-8 characters take one to four bytes. A chunk boundary can fall inside a character. Calling toString() on each chunk then produces replacement characters. Fix it with string_decoder.StringDecoder, which keeps incomplete bytes until the next chunk, or by calling stream.setEncoding('utf8').
Always validate lengths from untrusted input before allocating a buffer, otherwise a client can request a huge allocation.
const { StringDecoder } = require('node:string_decoder');
// 1. Build and parse a small binary packet: magic(2) | version(1) | id(4, LE) | marks(8, double BE)
const packet = Buffer.alloc(15);
packet.writeUInt16BE(0xcafe, 0);
packet.writeUInt8(1, 2);
packet.writeUInt32LE(70001, 3);
packet.writeDoubleBE(87.5, 7);
console.log('packet hex:', packet.toString('hex'));
console.log('parsed:', {
magic: packet.readUInt16BE(0).toString(16),
version: packet.readUInt8(2),
id: packet.readUInt32LE(3),
marks: packet.readDoubleBE(7),
});
// 2. The same number in the two byte orders.
const two = Buffer.alloc(2);
two.writeUInt16BE(0x0102);
const be = two.toString('hex');
two.writeUInt16LE(0x0102);
console.log('0x0102 as BE:', be, '| as LE:', two.toString('hex'));
// 3. A multi-byte word cut between chunks.
const word = 'नमस्ते';
const bytes = Buffer.from(word);
const chunk1 = bytes.subarray(0, 4);
const chunk2 = bytes.subarray(4);
const naive = chunk1.toString() + chunk2.toString();
const decoder = new StringDecoder('utf8');
const safe = decoder.write(chunk1) + decoder.write(chunk2) + decoder.end();
console.log('naive toString matches original:', naive === word);
console.log('StringDecoder matches original: ', safe === word);The packet layout is made up for the example. Part 3 cuts the 18 bytes of a Hindi word at byte 4, in the middle of the second letter. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): packet hex: cafe01711101004055e00000000000 parsed: { magic: 'cafe', version: 1, id: 70001, marks: 87.5 } 0x0102 as BE: 0102 | as LE: 0201 naive toString matches original: false StringDecoder matches original: true
Key points
- Use read/write methods with an explicit endianness.
- Network byte order is big-endian.
- Length-prefixed packets need a leftover buffer for partial data.
- StringDecoder or setEncoding prevents broken multi-byte characters.
- Validate length fields from untrusted data.
Common mistakes
- Mixing up big-endian and little-endian when two systems talk.
- Calling chunk.toString() on every stream chunk of text.
- Trusting a length field and allocating a buffer of that size.
- Assuming one data event equals one whole message.
Follow-ups
- How do you frame messages on a TCP stream?
- When would you use DataView instead of Buffer methods?
- How do you handle 64-bit integers safely in JavaScript?
Tips
- Draw the packet layout with offsets before writing code.
- Link the chunk problem to a real one: text files read in 64 KB pieces.
- Mention length limits as a security check.