Node.js Buffers
JavaScript strings are great for text, but files, network packets, images and encrypted data are raw bytes. Node.js represents a sequence of bytes with the Buffer class. A Buffer is a fixed-length block of memory where each element is an integer from 0 to 255. You meet buffers everywhere: fs.readFile() without an encoding returns one, HTTP request chunks are buffers, and crypto functions return them.
Buffer is a global, but you can import it explicitly with import { Buffer } from 'node:buffer'. It is a subclass of the standard Uint8Array, so all typed-array methods work on it too.
Creating buffers
| Function | Creates |
|---|---|
Buffer.from('text', 'utf8') |
bytes of a string in an encoding |
Buffer.from([72, 105]) |
bytes from an array of numbers |
Buffer.alloc(size, fill?) |
a zero-filled (or filled) buffer |
Buffer.allocUnsafe(size) |
uninitialized memory — faster, but may contain old data |
Buffer.concat([a, b]) |
one buffer joined from several |
const a = Buffer.from('Hi!');
const b = Buffer.from([0x4e, 0x6f, 0x64, 0x65]);
const c = Buffer.alloc(4);
const d = Buffer.alloc(3, 'ab');
console.log(a);
console.log(b, b.toString());
console.log(c);
console.log(d.toString());
console.log(a.length, a[0], a instanceof Uint8Array);<Buffer 48 69 21>
<Buffer 4e 6f 64 65> Node
<Buffer 00 00 00 00>
aba
3 72 true
When printed, a buffer shows each byte in hexadecimal. 0x48 is 72, the code of the letter H.
Note: Never use
new Buffer(...)— that constructor is deprecated because it could expose uninitialized memory. UseBuffer.from()andBuffer.alloc().
Bytes vs. characters
In UTF-8, English letters take one byte each, but accented letters take two, many Asian characters three, and emoji four. That's why the byte length of a string is often larger than its .length:
for (const text of ['cat', 'café', 'Việt', '日本', '🚀']) {
console.log(text.padEnd(5), 'chars:', text.length, 'bytes:', Buffer.byteLength(text));
}
const rocket = Buffer.from('🚀');
console.log(rocket);
console.log(rocket.subarray(0, 2).toString());cat chars: 3 bytes: 3
café chars: 4 bytes: 5
Việt chars: 4 bytes: 6
日本 chars: 2 bytes: 6
🚀 chars: 2 bytes: 4
<Buffer f0 9f 9a 80>
�
The emoji takes four bytes (and even its .length is 2, because JavaScript strings count UTF-16 code units). Cutting it after two bytes produces invalid UTF-8, which decodes to the replacement character �. When you receive text in chunks (for example from a stream), never decode each chunk on its own — join the buffers first, or use setEncoding('utf8') on the stream, which handles split characters for you.
Tip: Use
Buffer.byteLength(str)for theContent-LengthHTTP header —str.lengthis wrong as soon as the text contains non-ASCII characters.
Encodings
buf.toString(encoding) and Buffer.from(string, encoding) convert between bytes and text. Besides utf8 (the default), the most useful encodings are:
| Encoding | Example of Buffer.from('Hi!') |
Used for |
|---|---|---|
utf8 |
Hi! |
normal text |
hex |
486921 |
hashes, debugging |
base64 |
SGkh |
email attachments, data URLs, JSON payloads |
base64url |
SGkh |
tokens in URLs (uses - and _, no padding) |
latin1 |
Hi! |
old single-byte text |
const secret = Buffer.from('user:p@ss');
const b64 = secret.toString('base64');
console.log(b64);
console.log('Authorization: Basic ' + b64);
console.log(Buffer.from(b64, 'base64').toString('utf8'));
console.log(secret.toString('hex'));
console.log(Buffer.from('757365723a', 'hex').toString());
console.log(Buffer.from('??>>').toString('base64'), Buffer.from('??>>').toString('base64url'));dXNlcjpwQHNz
Authorization: Basic dXNlcjpwQHNz
user:p@ss
757365723a70407373
user:
Pz8+Pg== Pz8-Pg
Reading and writing numbers
Binary file formats and network protocols store numbers in a fixed number of bytes. Buffers have methods for each size and byte order (BE = big-endian, LE = little-endian):
const buf = Buffer.alloc(8);
buf.writeUInt16BE(500, 0); // 2 bytes
buf.writeInt16LE(-2, 2); // 2 bytes
buf.writeFloatBE(1.5, 4); // 4 bytes
console.log(buf);
console.log(buf.readUInt16BE(0), buf.readInt16LE(2), buf.readFloatBE(4));
const copy = Buffer.from(buf);
copy[0] = 0xff;
const view = buf.subarray(0, 2);
view[1] = 0x00;
console.log(buf.readUInt16BE(0), copy.readUInt16BE(0));
console.log(Buffer.compare(Buffer.from('a'), Buffer.from('b')), Buffer.from('ok').equals(Buffer.from('ok')));<Buffer 01 f4 fe ff 3f c0 00 00>
500 -2 1.5
256 65524
-1 true
subarray() returns a view that shares memory with the original — changing view changed buf. Buffer.from(buf) makes an independent copy.
Common methods
| Method | Description |
|---|---|
buf.toString(enc, start, end) |
decode bytes to text |
buf.subarray(start, end) |
view on part of the buffer (no copy) |
buf.equals(other) / Buffer.compare(a, b) |
compare contents |
buf.indexOf(value) / buf.includes(value) |
search for bytes or text |
buf.fill(value) |
overwrite every byte |
buf.toJSON() |
{ type: 'Buffer', data: [...] } |
Test yourself
What does Buffer.byteLength('é') return?
- 1
- 2
- 3
- 4
Which method creates a buffer that shares memory with the original?
Buffer.from(buf)buf.subarray(0, 4)Buffer.concat([buf])Buffer.alloc(4)
How do you decode the base64 text SGkh to a string?
Buffer.from('SGkh').toString('base64')Buffer.from('SGkh', 'base64').toString()atob(Buffer('SGkh'))Buffer.decode('SGkh')