Buffers and encoding
Overview
Computers store everything — text, images, video, network packets — as bytes: numbers from 0 to 255. Browser JavaScript mostly hides this from you. On a server you deal with bytes constantly: files are bytes, HTTP bodies are bytes, uploaded images are bytes, password hashes are bytes.
Node represents a chunk of bytes as a Buffer. Understanding Buffers and encodings — the rules for turning text into bytes and back — prevents a whole class of bugs with garbled characters and corrupted files.
Creating Buffers
const a = Buffer.from('hello'); // from a string (UTF-8 by default)
const b = Buffer.from([104, 105]); // from byte values → 'hi'
const c = Buffer.alloc(16); // 16 zero bytes
const d = Buffer.from('68656c6c6f', 'hex'); // from hex text
console.log(a); // <Buffer 68 65 6c 6c 6f>
console.log(a.length); // 5 (bytes)
console.log(a[0]); // 104 — the byte value of 'h'Buffers are fixed-size and behave like arrays of numbers (they’re a subclass of Uint8Array). You get them back from readFile without an encoding, from streams, from crypto, and from network sockets.
Text and encodings
An encoding defines how characters become bytes. The universal standard today is UTF-8, which uses 1 byte for plain English letters and digits, and 2 to 4 bytes for other characters — accented letters, Hindi, Chinese, emoji.
That’s why string length and byte length differ:
const name = 'नमस्ते';
name.length; // 6 (UTF-16 code units)
Buffer.byteLength(name, 'utf8'); // 18 bytesThis matters whenever there’s a size limit in bytes: database column sizes, HTTP Content-Length headers, upload limits, SMS messages.
Converting
const buf = Buffer.from('café', 'utf8');
buf.toString('utf8'); // 'café'
buf.toString('hex'); // '636166c3a9'
buf.toString('base64'); // 'Y2Fmw6k='Node supports 'utf8', 'utf16le', 'latin1', 'ascii', 'hex', 'base64' and 'base64url'. If you read a file saved in an old encoding such as Windows-1252, decode it explicitly — TextDecoder supports many more encodings than Buffer does:
const text = new TextDecoder('windows-1252').decode(bytes);Hex and base64
Binary data often needs to travel through places that only accept text: JSON, URLs, HTTP headers, environment variables. Two encodings turn any bytes into safe text:
- Hex — two characters per byte (
0-9a-f). Easy to read; doubles the size. Common for hashes and tokens. - Base64 — about four characters per three bytes. Compact; used for email attachments, data URLs, HTTP Basic auth and JWTs.
- base64url — base64 with
-and_instead of+and/, and no=padding, so it’s safe inside URLs.
import { randomBytes } from 'node:crypto';
const token = randomBytes(32);
token.toString('hex'); // 64 characters
token.toString('base64url'); // 43 characters, URL-safe
// HTTP Basic auth header
const header = 'Basic ' + Buffer.from('asha:s3cret').toString('base64');Base64 is not encryption. Anyone can decode it in one line. It only makes binary data text-safe.
Working with bytes
const buf = Buffer.from('Hello, Node!');
buf.subarray(0, 5).toString(); // 'Hello' — shares memory with buf
buf.includes('Node'); // true
buf.indexOf(','); // 5
Buffer.concat([Buffer.from('a'), Buffer.from('b')]); // <Buffer 61 62>
buf.equals(Buffer.from('Hello, Node!')); // trueMany file formats start with a “magic number” that identifies them. Checking it is more reliable than trusting a file’s extension:
const header = (await readFile('upload.bin')).subarray(0, 4);
const isPdf = header.toString('latin1') === '%PDF';Collecting chunks correctly
When data arrives in chunks (from a stream or a request), don’t join them with + or +=:
// ✗ A multi-byte character split across two chunks gets corrupted
let body = '';
req.on('data', (chunk) => { body += chunk; });A character like é is two bytes. If one chunk ends after the first byte, converting that chunk to a string on its own produces �. Collect the raw Buffers and decode once at the end:
// ✓
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
const body = Buffer.concat(chunks).toString('utf8');Or use the helpers in node:stream/consumers — text(stream), json(stream), buffer(stream) — which do this for you.
Comparing secrets safely
When checking a secret value such as an API key or a signature, a normal === comparison can leak information through tiny timing differences. Use crypto.timingSafeEqual with Buffers of equal length:
import { timingSafeEqual } from 'node:crypto';
function safeCompare(a, b) {
const bufA = Buffer.from(a);
const bufB = Buffer.from(b);
return bufA.length === bufB.length && timingSafeEqual(bufA, bufB);
}Remember: text is for people; bytes are for machines. Decide the encoding at the boundary — when reading a file, receiving a request, or sending a response — and work with proper strings everywhere in between.
Base64 helpers
Write toBase64Url(text) and fromBase64Url(encoded) that convert UTF-8 text to URL-safe base64 and back. Test them with a string containing an emoji. Then write isPng(buffer) that checks a file's first 8 bytes match the PNG signature 89 50 4E 47 0D 0A 1A 0A.
export function toBase64Url(text) {}
export function fromBase64Url(encoded) {}
export function isPng(buffer) {}const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
export function toBase64Url(text) {
return Buffer.from(text, 'utf8').toString('base64url');
}
export function fromBase64Url(encoded) {
return Buffer.from(encoded, 'base64url').toString('utf8');
}
export function isPng(buffer) {
return buffer.length >= 8 && buffer.subarray(0, 8).equals(PNG_SIGNATURE);
}
fromBase64Url(toBase64Url('Hi 👋')); // 'Hi 👋'Summary
- A Buffer is a fixed-size sequence of bytes (0–255) — how Node represents binary data.
- Text becomes bytes through an encoding; UTF-8 is the default and uses 1–4 bytes per character.
- Convert with
Buffer.from(text, 'utf8')andbuffer.toString(encoding). - Hex and base64 turn bytes into text-safe strings; base64url is safe in URLs.
- Never join Buffers from a stream with
+; collect them and useBuffer.concat.