π¦ What Is a Buffer?
A Buffer is a fixed-size chunk of memory for handling raw binary data β the kind of data you get from files, network requests, or streams, before it's been decoded into text.
Unlike a string, a buffer works directly with bytes, not characters. It's a global in Node.js β no require needed.
const buf = Buffer.from('hello');
console.log(buf);
// <Buffer 68 65 6c 6c 6f>Each number in the output (
68 65 6c 6c 6f) is one byte, shown in hexadecimal β the raw bytes that make up"hello"when encoded as UTF-8.Buffers exist because JavaScript strings weren't built for binary data β things like image files or network packets need a byte-level representation.
ποΈ Creating Buffers
const fromString = Buffer.from('hello'); // from a string
const fromArray = Buffer.from([104, 101, 108, 108, 111]); // from byte values
const empty = Buffer.alloc(10); // 10 zeroed-out bytes
const fast = Buffer.allocUnsafe(10); // 10 bytes, uninitialized (faster, unsafe)Buffer.from(string)builds a buffer from existing data β a string, an array of byte values, or another buffer.Buffer.alloc(size)creates a buffer of a given size, filled with zeros β safe to use right away.Buffer.allocUnsafe(size)creates a buffer faster, but skips zeroing it out β it may contain leftover data from memory. Only use it if you're about to overwrite every byte yourself.
β οΈ Avoid new Buffer() β it's deprecated. Buffer.from() and Buffer.alloc() replaced it because the old constructor's behavior changed depending on what type of argument you passed, which caused security bugs.
<div class="infographic-buffer">
<style>
.infographic-buffer {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb;
--accent-soft:#e3ebfd;
--line: #ddd6c9;
--charge: #c23b3b;
--charge-soft:#fbe6e6;
--radius: 10px;
box-sizing: border-box;
max-width: 880px;
margin: 0 auto;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
color: var(--ink);
background: transparent;
}
.infographic-buffer[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #13171F;
--paper-alt: #1e1e26;
--accent: #5b8def;
--accent-soft:#202942;
--line: #2c313d;
--charge: #e2685f;
--charge-soft:#3a2020;
}
.infographic-buffer * { box-sizing: border-box; }
.infographic-buffer .ib-inner { padding: 0 clamp(1rem, 4vw, 1.5rem); }
.infographic-buffer .ib-eyebrow {
font-size: 0.7rem; font-weight: 600; letter-spacing: 0.09em;
text-transform: uppercase; color: var(--accent); margin: 0 0 0.35rem;
}
.infographic-buffer h2 {
font-family: 'Newsreader', Georgia, serif; font-weight: 600;
font-size: clamp(1.5rem, 4vw, 2rem); line-height: 1.15;
margin: 0 0 0.3rem; letter-spacing: -0.01em;
}
.infographic-buffer .ib-sub { font-size: 0.9rem; color: var(--ink-soft); margin: 0 0 1rem; }
/* ---------- example chips ---------- */
.infographic-buffer .ib-chips { display: flex; gap: 0.4rem; flex-wrap: wrap; margin-bottom: 1rem; }
.infographic-buffer .ib-chip {
font: inherit; font-size: 0.78rem; color: var(--ink-soft); background: var(--paper);
border: 1px solid var(--line); border-radius: 999px; padding: 0.32rem 0.75rem;
cursor: pointer; transition: border-color 0.15s ease, color 0.15s ease;
}
.infographic-buffer .ib-chip:hover { border-color: var(--accent); color: var(--ink); }
/* ---------- Playground card ---------- */
.infographic-buffer .ib-play {
border: 1px solid var(--line); border-radius: var(--radius); background: var(--paper-alt);
padding: 1.1rem 1.15rem 1.2rem;
}
.infographic-buffer .ib-play-top {
display: flex; align-items: center; gap: 0.6rem; margin-bottom: 0.9rem; flex-wrap: wrap;
}
.infographic-buffer .ib-input {
flex: 1; min-width: 140px; font-family: 'SFMono-Regular', Consolas, Menlo, monospace;
font-size: 0.95rem; padding: 0.5rem 0.7rem; border: 1px solid var(--line); border-radius: 8px;
background: var(--paper); color: var(--ink);
}
.infographic-buffer .ib-input:focus { outline: 2px solid var(--accent); outline-offset: 1px; }
.infographic-buffer .ib-count {
flex: none; font-family: 'SFMono-Regular', Consolas, Menlo, monospace; font-size: 0.75rem;
font-weight: 700; color: var(--accent); background: var(--accent-soft);
border-radius: 999px; padding: 0.3rem 0.65rem; white-space: nowrap;
transition: transform 0.2s ease;
}
.infographic-buffer .ib-count.is-bump { transform: scale(1.12); }
.infographic-buffer .ib-pills { display: flex; gap: 0.4rem; margin-bottom: 1rem; }
.infographic-buffer .ib-pill {
font-family: inherit; font-size: 0.74rem; font-weight: 600; color: var(--ink-soft);
background: var(--paper); border: 1px solid var(--line); border-radius: 999px;
padding: 0.32rem 0.75rem; cursor: pointer; transition: all 0.15s ease;
}
.infographic-buffer .ib-pill:hover { border-color: var(--accent); }
.infographic-buffer .ib-pill.is-on { background: var(--accent); border-color: var(--accent); color: #fff; }
.infographic-buffer .ib-strip { display: flex; flex-wrap: wrap; gap: 0.4rem; perspective: 600px; }
.infographic-buffer .ib-cell { width: 56px; height: 44px; }
.infographic-buffer .ib-flip {
width: 100%; height: 100%; position: relative; transform-style: preserve-3d;
transition: transform 0.45s ease; cursor: pointer;
}
.infographic-buffer .ib-cell.is-flipped .ib-flip { transform: rotateY(180deg); }
.infographic-buffer .ib-face {
position: absolute; inset: 0; backface-visibility: hidden; border-radius: 7px;
border: 1px solid var(--line); background: var(--paper);
display: flex; align-items: center; justify-content: center;
font-family: 'SFMono-Regular', Consolas, Menlo, monospace; font-weight: 600;
font-size: 0.8rem; color: var(--ink);
transition: border-color 0.15s ease, opacity 0.28s ease, transform 0.28s ease;
opacity: 0; transform: translateY(6px) scale(0.85);
}
.infographic-buffer .ib-cell.is-in .ib-face-front { opacity: 1; transform: translateY(0) scale(1); }
.infographic-buffer .ib-cell:hover .ib-face-front { border-color: var(--accent); }
.infographic-buffer .ib-face-back {
transform: rotateY(180deg); background: var(--accent-soft); border-color: var(--accent);
flex-direction: column; gap: 0.05rem; font-size: 0.58rem; font-weight: 500; padding: 0.2rem;
line-height: 1.35; opacity: 1;
}
.infographic-buffer .ib-cell.is-flipped .ib-face-back { opacity: 1; }
.infographic-buffer .ib-face-back b { font-size: 0.66rem; color: var(--accent); }
/* idle pulse hint on very first cell, until any block is clicked */
.infographic-buffer .ib-cell.is-hint .ib-face-front::after {
content: ''; position: absolute; inset: -4px; border-radius: 10px;
border: 2px solid var(--accent); opacity: 0; animation: ib-ring 1.7s ease-out infinite;
}
@keyframes ib-ring {
0% { opacity: 0.55; transform: scale(0.9); }
70% { opacity: 0; transform: scale(1.28); }
100% { opacity: 0; }
}
@media (prefers-reduced-motion: reduce) {
.infographic-buffer .ib-cell.is-hint .ib-face-front::after { animation: none; opacity: 0; }
}
.infographic-buffer .ib-strip-hint {
font-size: 0.75rem; color: var(--ink-soft); margin-top: 0.65rem; opacity: 0.85;
}
/* ---------- Creation methods ---------- */
.infographic-buffer .ib-methods { margin-top: 1.6rem; }
.infographic-buffer .ib-method-row { display: flex; gap: 0.55rem; flex-wrap: wrap; margin-bottom: 0.9rem; }
.infographic-buffer .ib-method-btn {
display: flex; flex-direction: column; align-items: center; gap: 0.35rem;
border: 1px solid var(--line); border-radius: var(--radius); background: var(--paper-alt);
padding: 0.6rem 0.8rem; cursor: pointer; font: inherit; color: var(--ink-soft);
transition: border-color 0.15s ease, background 0.15s ease; min-width: 84px;
}
.infographic-buffer .ib-method-btn:hover { border-color: var(--accent); }
.infographic-buffer .ib-method-btn.is-on { border-color: var(--accent); background: var(--accent-soft); color: var(--ink); }
.infographic-buffer .ib-method-btn .ib-m-icon {
width: 30px; height: 30px; border-radius: 8px; background: var(--paper); border: 1px solid var(--line);
display: flex; align-items: center; justify-content: center;
box-shadow: 0 1px 3px rgba(0,0,0,0.10), 0 1px 1px rgba(0,0,0,0.06);
}
.infographic-buffer[data-theme="dark"] .ib-method-btn .ib-m-icon { box-shadow: 0 1px 4px rgba(0,0,0,0.45); }
.infographic-buffer .ib-method-btn svg { width: 15px; height: 15px; stroke: var(--accent); }
.infographic-buffer .ib-method-btn span.ib-m-label { font-size: 0.68rem; font-weight: 600; font-family: 'SFMono-Regular', Consolas, Menlo, monospace; }
.infographic-buffer .ib-demo {
border: 1px solid var(--line); border-radius: var(--radius); background: var(--paper);
padding: 0.9rem 1rem; display: flex; align-items: center; gap: 1rem; flex-wrap: wrap;
}
.infographic-buffer .ib-demo-strip { display: flex; gap: 0.3rem; flex-wrap: wrap; }
.infographic-buffer .ib-demo-cell {
width: 34px; height: 32px; border-radius: 6px; border: 1px solid var(--line);
background: var(--paper-alt); display: flex; align-items: center; justify-content: center;
font-family: 'SFMono-Regular', Consolas, Menlo, monospace; font-size: 0.66rem; font-weight: 600;
color: var(--ink-soft); opacity: 0; transform: scale(0.6);
transition: opacity 0.25s ease, transform 0.25s ease, background 0.2s ease, color 0.2s ease;
}
.infographic-buffer .ib-demo-cell.is-in { opacity: 1; transform: scale(1); }
.infographic-buffer .ib-demo-cell.is-data { background: var(--accent-soft); color: var(--accent); border-color: var(--accent); }
.infographic-buffer .ib-demo-cell.is-zero { background: var(--paper-alt); color: var(--ink-soft); }
.infographic-buffer .ib-demo-cell.is-junk { background: var(--charge-soft); color: var(--charge); border-color: var(--charge); }
.infographic-buffer .ib-demo-caption { font-size: 0.78rem; font-weight: 600; color: var(--ink-soft); font-family: 'SFMono-Regular', Consolas, Menlo, monospace; }
.infographic-buffer .ib-demo-caption.is-warn { color: var(--charge); }
.infographic-buffer .ib-deprecated {
display: inline-flex; align-items: center; gap: 0.35rem; margin-top: 0.9rem;
font-size: 0.72rem; color: var(--charge); background: var(--charge-soft);
border: 1px solid var(--charge); border-radius: 999px; padding: 0.28rem 0.7rem;
font-family: 'SFMono-Regular', Consolas, Menlo, monospace;
}
.infographic-buffer .ib-deprecated svg { width: 12px; height: 12px; stroke: var(--charge); flex: none; }
</style>
<div class="ib-inner">
<div class="ib-chips">
<button class="ib-chip" data-val="Hi there!" type="button">π¬ a chat message</button>
<button class="ib-chip" data-val="GET /ping" type="button">π a network request</button>
<button class="ib-chip" data-val="π" type="button">π one emoji</button>
</div>
<div class="ib-play">
<div class="ib-play-top">
<input class="ib-input" id="ibInput" type="text" value="hello" spellcheck="false" />
<span class="ib-count" id="ibCount">5 bytes</span>
</div>
<div class="ib-pills" id="ibPills">
<button class="ib-pill is-on" data-fmt="hex" type="button">hex</button>
<button class="ib-pill" data-fmt="dec" type="button">dec</button>
<button class="ib-pill" data-fmt="char" type="button">char</button>
<button class="ib-pill" data-fmt="bin" type="button">binary</button>
</div>
<div class="ib-strip" id="ibStrip"></div>
<p class="ib-strip-hint" id="ibStripHint">tap a block to see all its forms</p>
</div>
<div class="ib-methods">
<div class="ib-method-row" id="ibMethods">
<button class="ib-method-btn is-on" data-m="fromstring" type="button">
<span class="ib-m-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h-1a2 2 0 0 1-2-2 2 2 0 0 1-2 2H6"/><path d="M13 8h7a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-7"/><path d="M5 16H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h1"/><path d="M6 4h1a2 2 0 0 1 2 2 2 2 0 0 1 2-2h1"/><path d="M9 6v12"/></svg></span>
<span class="ib-m-label">from(str)</span>
</button>
<button class="ib-method-btn" data-m="fromarray" type="button">
<span class="ib-m-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 3h3a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1h-3"/><path d="M8 21H5a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h3"/></svg></span>
<span class="ib-m-label">from(arr)</span>
</button>
<button class="ib-method-btn" data-m="alloc" type="button">
<span class="ib-m-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/></svg></span>
<span class="ib-m-label">alloc</span>
</button>
<button class="ib-method-btn" data-m="allocunsafe" type="button">
<span class="ib-m-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/></svg></span>
<span class="ib-m-label">allocUnsafe</span>
</button>
</div>
<div class="ib-demo">
<div class="ib-demo-strip" id="ibDemoStrip"></div>
<span class="ib-demo-caption" id="ibDemoCaption">instant, from text</span>
</div>
<span class="ib-deprecated">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>
new Buffer() β deprecated
</span>
</div>
</div>
<script>
(function () {
var wrapper = document.currentScript.closest('.infographic-buffer')
|| document.querySelector('.infographic-buffer');
var bodyAttr = document.body.getAttribute('data-darkmode');
var dark;
if (bodyAttr === 'true') { dark = true; }
else if (bodyAttr === 'false') { dark = false; }
else {
var match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
if (dark) wrapper.setAttribute('data-theme', 'dark');
var reduced = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var hasInteracted = false;
/* ============ example chips ============ */
var chips = Array.prototype.slice.call(wrapper.querySelectorAll('.ib-chip'));
/* ============ Playground: byte strip ============ */
var input = wrapper.querySelector('#ibInput');
var count = wrapper.querySelector('#ibCount');
var strip = wrapper.querySelector('#ibStrip');
var stripHint = wrapper.querySelector('#ibStripHint');
var pills = Array.prototype.slice.call(wrapper.querySelectorAll('.ib-pills .ib-pill'));
var fmt = 'hex';
function fmtVal(code, f) {
if (f === 'hex') return code.toString(16).padStart(2, '0');
if (f === 'dec') return String(code);
if (f === 'bin') return code.toString(2).padStart(8, '0');
return code >= 32 && code <= 126 ? "'" + String.fromCharCode(code) + "'" : '\u00b7';
}
function render(opts) {
opts = opts || {};
var val = input.value;
var bytes = Array.from(new TextEncoder().encode(val));
count.textContent = bytes.length + (bytes.length === 1 ? ' byte' : ' bytes');
count.classList.add('is-bump');
setTimeout(function () { count.classList.remove('is-bump'); }, 220);
var cells = Array.prototype.slice.call(strip.children);
while (cells.length > bytes.length) { strip.removeChild(cells.pop()); }
var startNew = cells.length;
while (cells.length < bytes.length) {
var cell = document.createElement('div');
cell.className = 'ib-cell';
cell.innerHTML =
'<div class="ib-flip">' +
'<div class="ib-face ib-face-front"></div>' +
'<div class="ib-face ib-face-back"></div>' +
'</div>';
cell.addEventListener('click', function () {
this.classList.toggle('is-flipped');
if (!hasInteracted) {
hasInteracted = true;
strip.querySelectorAll('.ib-cell.is-hint').forEach(function (c) { c.classList.remove('is-hint'); });
stripHint.style.display = 'none';
}
});
strip.appendChild(cell);
cells.push(cell);
}
cells.forEach(function (cell, i) {
var code = bytes[i];
var front = cell.querySelector('.ib-face-front');
var back = cell.querySelector('.ib-face-back');
front.textContent = fmtVal(code, fmt);
var hex = code.toString(16).padStart(2, '0');
var ch = code >= 32 && code <= 126 ? "'" + String.fromCharCode(code) + "'" : 'Β·';
back.innerHTML =
'<div>hex <b>' + hex + '</b></div>' +
'<div>dec <b>' + code + '</b></div>' +
'<div>chr <b>' + ch + '</b></div>';
var isNewlyAdded = i >= startNew || opts.replay;
if (isNewlyAdded && !reduced) {
cell.classList.remove('is-in');
var delay = (i - startNew) * 55;
setTimeout(function () { cell.classList.add('is-in'); }, Math.max(0, delay));
} else {
cell.classList.add('is-in');
}
});
if (!hasInteracted && cells.length) {
cells.forEach(function (c) { c.classList.remove('is-hint'); });
cells[0].classList.add('is-hint');
stripHint.style.display = '';
}
}
input.addEventListener('input', function () { render(); });
pills.forEach(function (p) {
p.addEventListener('click', function () {
pills.forEach(function (x) { x.classList.remove('is-on'); });
p.classList.add('is-on');
fmt = p.getAttribute('data-fmt');
render();
});
});
chips.forEach(function (chip) {
chip.addEventListener('click', function () {
input.value = chip.getAttribute('data-val');
render({ replay: true });
input.focus();
});
});
render({ replay: true });
/* ============ Creation methods demo ============ */
var methodBtns = Array.prototype.slice.call(wrapper.querySelectorAll('#ibMethods .ib-method-btn'));
var demoStrip = wrapper.querySelector('#ibDemoStrip');
var demoCaption = wrapper.querySelector('#ibDemoCaption');
var demoTimers = [];
var DEMO_N = 8;
var demoData = [104, 101, 108, 108, 111, 33, 63, 10];
function clearDemoTimers() { demoTimers.forEach(clearTimeout); demoTimers = []; }
function ensureDemoCells() {
demoStrip.innerHTML = '';
var cells = [];
for (var i = 0; i < DEMO_N; i++) {
var c = document.createElement('div');
c.className = 'ib-demo-cell';
demoStrip.appendChild(c);
cells.push(c);
}
return cells;
}
function playMethod(key) {
clearDemoTimers();
var cells = ensureDemoCells();
demoCaption.classList.remove('is-warn');
if (key === 'fromstring') {
demoCaption.textContent = 'instant, from text';
cells.forEach(function (c, i) {
var v = demoData[i].toString(16).padStart(2, '0');
var delay = reduced ? 0 : i * 70;
demoTimers.push(setTimeout(function () {
c.textContent = v; c.classList.add('is-in', 'is-data');
}, delay));
});
}
if (key === 'fromarray') {
demoCaption.textContent = 'instant, from numbers';
cells.forEach(function (c, i) {
var v = demoData[i].toString(16).padStart(2, '0');
var delay = reduced ? 0 : 60;
demoTimers.push(setTimeout(function () {
c.textContent = v; c.classList.add('is-in', 'is-data');
}, delay));
});
}
if (key === 'alloc') {
demoCaption.textContent = 'zero-filled, safe';
cells.forEach(function (c, i) {
var delay = reduced ? 0 : i * 55;
demoTimers.push(setTimeout(function () {
c.textContent = '00'; c.classList.add('is-in', 'is-zero');
}, delay));
});
}
if (key === 'allocunsafe') {
demoCaption.textContent = 'uninitialized β leftover bytes';
demoCaption.classList.add('is-warn');
cells.forEach(function (c, i) {
c.classList.add('is-in', 'is-junk');
var jitters = reduced ? 0 : 5;
var t = 0;
for (var j = 0; j < jitters; j++) {
t += 55;
(function (cell, tt) {
demoTimers.push(setTimeout(function () {
cell.textContent = Math.floor(Math.random() * 256).toString(16).padStart(2, '0');
}, tt + i * 20));
})(c, t);
}
});
}
}
methodBtns.forEach(function (btn) {
btn.addEventListener('click', function () {
methodBtns.forEach(function (b) { b.classList.remove('is-on'); });
btn.classList.add('is-on');
playMethod(btn.getAttribute('data-m'));
});
});
playMethod('fromstring');
})();
</script>
</div>π€ Converting Between Buffers and Strings
const buf = Buffer.from('hello world');
console.log(buf.toString()); // 'hello world' (defaults to utf8)
console.log(buf.toString('hex')); // '68656c6c6f20776f726c64'
console.log(buf.toString('base64')); // 'aGVsbG8gd29ybGQ='.toString()decodes the raw bytes back into a readable string.Passing an encoding (
'hex','base64', etc.) controls the format of the output β useful when sending binary data somewhere that only accepts text, like a URL or JSON.
π Reading Buffer Info
const buf = Buffer.from('hello');
console.log(buf.length); // 5 β number of bytes
console.log(buf[0]); // 104 β byte value at index 0.lengthgives the number of bytes, not characters β for most simple text these match, but multi-byte characters (emoji, accented letters) take up more than one byte each.Buffers support index access like arrays, but each index returns a raw byte number, not a character.
Next up: slicing, combining, writing, and comparing buffers β plus real-world examples of buffers in action.