Reading from Buffers
You'll learn how to extract data from Buffers by accessing individual bytes and reading multi-byte numeric values.
Now that you know how to create and encode Buffers, it's time to retrieve the data stored inside them. Think of a Buffer like a row of numbered boxes—you can peek into any box individually, or read several boxes together to reconstruct larger values.
Accessing Individual Bytes
Use bracket notation (like arrays) to read a single byte at any position. Each value is a number between 0 and 255:
const buf = Buffer.from('Hello');
console.log(buf[0]); // 72 (the byte value for 'H')
console.log(buf[1]); // 101 (the byte value for 'e')
console.log(buf[4]); // 111 (the byte value for 'o')
Reading Multi-Byte Values
For numbers that span multiple bytes (like integers or floats), use the readInt and readUInt methods. These interpret consecutive bytes as a single numeric value:
const numBuf = Buffer.alloc(4);
numBuf.writeInt32LE(305419896, 0); // Write a 4-byte integer
// Read it back
const value = numBuf.readInt32LE(0);
console.log(value); // 305419896
// Or read as unsigned
const uValue = numBuf.readUInt32LE(0);
console.log(uValue); // Same value interpreted as unsigned
The method names indicate:
- Int vs UInt: signed vs unsigned
- Number: bit size (8, 16, 32)
- LE vs BE: little-endian vs big-endian byte order
The parameter is the starting offset (which byte position to begin reading from).
Key Takeaway: Access Buffer bytes with indexing for single bytes, or use readInt/readUInt methods to interpret multi-byte numeric values stored in specific formats.