Buffers and binary data

Intermediate · 10 min

Buffer as a Uint8Array subclass, encodings, alloc versus allocUnsafe, copying versus sharing memory, reading integers, concat, and split multibyte characters.

Before thisThe file system with fs/promises

Codevolution · 10 min

Buffers and binary data

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodevolutionReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A `Buffer` is a fixed-length block of raw bytes, and since Node 4 it is a subclass of `Uint8Array`. Files, sockets and crypto all deal in bytes, and strings are only one way to interpret them.
  • `Buffer.from(string, encoding)` and `buf.toString(encoding)` convert between text and bytes. `length` counts bytes, not characters: `'héllo €'` is 7 characters and 10 bytes in UTF-8.
  • `Buffer.alloc(n)` returns zeroed memory. `Buffer.allocUnsafe(n)` is faster but may contain old data from other parts of the process, so only use it when you overwrite every byte.
  • `subarray` returns a view that shares memory with the original, while `Buffer.from(buf)` copies. Writing through a view changes the original.
  • Converting chunks of a multibyte string one at a time with `toString` can corrupt characters that straddle a chunk boundary. Concatenate the buffers first, or use `StringDecoder`.

Why bytes at all

A string is text: a sequence of characters. A file on disk, a TCP packet and a hash are sequences of bytes. To go from one to the other you must choose an encoding, a rule such as UTF-8 that says how characters become bytes. JavaScript the language has strings and, through typed arrays, byte arrays (typed arrays and ArrayBuffer). Node needed to read files and sockets before typed arrays existed, so it created Buffer. Today a Buffer is a Uint8Array with extra methods for encodings and integers:

const b = Buffer.from('héllo €', 'utf8');
console.log(b);                       // <Buffer 68 c3 a9 6c 6c 6f 20 e2 82 ac>
console.log(b.length, 'héllo €'.length);   // 10 7
console.log(b instanceof Uint8Array);      // true

Ten bytes, seven characters. é took two bytes (c3 a9) and € three (e2 82 ac). This is why length on a buffer is a byte count, and why slicing a string at a byte offset is wrong.

Encodings

Buffer.from(text, encoding) encodes and buf.toString(encoding) decodes. The encodings you will use:

const b = Buffer.from('héllo €');
b.toString('hex');         // '68c3a96c6c6f20e282ac'
b.toString('base64');      // 'aMOpbGxvIOKCrA=='
b.toString('base64url');   // 'aMOpbGxvIOKCrA'  (URL-safe, no padding)
Buffer.from('aGk=', 'base64').toString();   // 'hi'
Buffer.from('6869', 'hex').toString();      // 'hi'

utf8 is the default for text. hex and base64 are how hashes, keys and binary data travel as text in JSON and URLs. base64url is the variant used in JWTs and URLs. If you want the encoded size without allocating, Buffer.byteLength('€') is 3.

For code that should also run in browsers, TextEncoder and TextDecoder do the UTF-8 conversion on plain Uint8Arrays and are globals in Node.

Creating buffers

Buffer.alloc(4);                 // <Buffer 00 00 00 00>   zero-filled
Buffer.alloc(3, 1);              // <Buffer 01 01 01>      filled with 1
Buffer.allocUnsafe(2);           // two bytes of whatever was in memory
Buffer.from([1, 2, 3]);          // from an array of byte values
Buffer.concat([Buffer.from('ab'), Buffer.from('cd')]).toString();   // 'abcd'

allocUnsafe is faster because it draws from a shared pool and skips zeroing. The catch: the memory can contain leftover bytes from earlier operations. If you allocate it and send it without writing every byte, you may leak data. Reach for alloc unless a profile tells you otherwise. Buffer.concat is the correct way to join chunks, as in streams: never + them, which turns each into a string.

Copy or share

Byte memory is easy to share by accident. Compare:

const a = Buffer.from([1, 2, 3]);
const view = a.subarray(1);
view[0] = 99;
console.log(a, view.buffer === a.buffer);   // <Buffer 01 63 03> true

const copy = Buffer.from(a);                 // copies the bytes
copy[0] = 0;
console.log(a[0]);                            // 1  (unchanged)

subarray is a view onto the same memory, so writing through it changes the original. Buffer.from(buffer) copies. Passing an ArrayBuffer to Buffer.from shares it. If a buffer travels far from where it was made, such as into a cache, copy it, or someone else’s write can corrupt it.

Reading and writing numbers

Binary protocols pack numbers into bytes with a fixed size and byte order. Buffer has methods for it:

const hdr = Buffer.alloc(8);
hdr.writeUInt32BE(0xcafebabe, 0);   // 4 bytes, big-endian, at offset 0
hdr.writeUInt16LE(513, 4);           // 2 bytes, little-endian, at offset 4
hdr.writeInt8(-1, 6);                // 1 signed byte
console.log(hdr);                    // <Buffer ca fe ba be 01 02 ff 00>
hdr.readUInt32BE(0).toString(16);    // 'cafebabe'

BE is big-endian (most significant byte first, the network standard) and LE is little-endian (what most CPUs use). Mixing them up is the classic binary-format bug. Comparison helpers: Buffer.compare(a, b) returns -1, 0 or 1, and a.equals(b) compares contents. JSON.stringify(buf) produces { "type": "Buffer", "data": [...] }, which is rarely what you want; use toString('base64') instead.

Multibyte characters across chunks

This is the bug that shows up only with real data. A € is three bytes. If a stream delivers it in two pieces and you decode each piece separately:

const euro = Buffer.from('€');
euro.subarray(0, 2).toString();                                  // '�'  (replacement char)
Buffer.concat([euro.subarray(0, 2), euro.subarray(2)]).toString();   // '€'

import { StringDecoder } from 'node:string_decoder';
const d = new StringDecoder('utf8');
d.write(euro.subarray(0, 2)) + d.write(euro.subarray(2));        // '€'

Decoding each half alone produces the replacement character. Either collect all the chunks with Buffer.concat and decode once, or use StringDecoder, which keeps incomplete bytes until the rest arrives. Setting stream.setEncoding('utf8') uses a decoder for you.

Newer helpers

Recent V8 versions add Uint8Array.prototype.toHex() and Uint8Array.fromBase64(). Both exist on Node 26.13.1 (typeof returns 'function'), but they are new, so confirm they exist on the Node line you deploy before using them, and fall back to Buffer methods on older ones.

What the video covers

Codevolution’s ten-minute video is titled “Streams and Buffers” and, as the title says, splits its time between the two. The buffer section introduces what a buffer is and how Node uses it for binary data. Encodings, alloc versus allocUnsafe, views versus copies, integer reads and the chunk-boundary bug are covered by the prose, run on Node 26.13.1. The video is from December 2022. A fresher Buffer-only video from October 2026 exists but comes from a channel with about a hundred subscribers, so it was not used. No transcript was available.

Where this fits

Buffers are the unit streams move around. Why streams starts the next group’s story, and hashing, HMAC and randomness with crypto is where hex and base64 outputs show up constantly.

Check yourself

  1. 01`'héllo €'.length` is 7 but `Buffer.from('héllo €').length` is 10. Why?

    String length counts UTF-16 code units, which here is one per visible character. A buffer counts bytes, and in UTF-8 `é` takes two bytes and `€` takes three. `Buffer.byteLength(str)` tells you the encoded size without building the buffer.

  2. 02What is the difference between `Buffer.alloc(8)` and `Buffer.allocUnsafe(8)`, and when is the unsafe one acceptable?

    `alloc` fills the memory with zeros. `allocUnsafe` skips the filling, so it can expose leftover bytes from earlier allocations, which is a data leak if you send them. Use it only when you immediately write every byte, for example when copying data into it.

  3. 03You do `const part = buf.subarray(1); part[0] = 99;`. Does `buf` change?

    Yes. `subarray` creates a view onto the same memory, so a write through `part` shows up in `buf`, and `part.buffer === buf.buffer` is true. Use `Buffer.from(buf.subarray(1))` when you need an independent copy. Note that `Buffer`'s own `slice` method also shares memory, unlike `Uint8Array.prototype.slice`, which copies.

  4. 04A UTF-8 stream delivers `€` split across two chunks. Why does decoding each chunk with `chunk.toString()` give garbage, and what fixes it?

    `€` is three bytes. A chunk holding only the first two cannot be decoded and becomes the replacement character, and the third byte then breaks too. Collect the chunks with `Buffer.concat` and decode once, or feed them through a `StringDecoder`, which holds incomplete bytes back until the rest arrives.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark