Buffer Encoding
You'll learn how to convert buffers to and from strings using different encoding formats.
What Is Buffer Encoding?
When you work with buffers, you often need to convert them to readable strings or create buffers from strings. The encoding specifies how binary data maps to text characters. Think of encoding as a translation dictionary—the same binary data can be interpreted differently depending on which dictionary (encoding) you use.
Common Encodings
Node.js supports several encodings:
utf8(default): Standard text encoding for most languageshex: Represents each byte as two hexadecimal charactersbase64: Compact representation using 64 ASCII characters (common for data URLs and APIs)ascii: 7-bit ASCII characters onlybinaryandlatin1: Single-byte encodings
Converting Between Buffers and Strings
// Create a buffer from a string with specific encoding
const buf = Buffer.from('Hello', 'utf8');
// Convert buffer to string with encoding
console.log(buf.toString('utf8')); // 'Hello'
console.log(buf.toString('hex')); // '48656c6c6f'
console.log(buf.toString('base64')); // 'SGVsbG8='
// Create buffer from hex encoding
const hexBuf = Buffer.from('48656c6c6f', 'hex');
console.log(hexBuf.toString('utf8')); // 'Hello'
// Create buffer from base64 encoding
const b64Buf = Buffer.from('SGVsbG8=', 'base64');
console.log(b64Buf.toString('utf8')); // 'Hello'
The same binary data (48 65 6c 6c 6f in hex) represents "Hello" in UTF-8, but appears completely different when viewed through the hex or base64 "lens."
Key Takeaway: Buffer encodings let you convert between binary buffers and text strings—use Buffer.from(string, encoding) to create buffers and buffer.toString(encoding) to read them, with utf8, hex, and base64 being the most common formats.