Node Buffers: Binary Data, Encodings, Reading and Writing Bytes
Work with raw bytes in Node: Buffer as a Uint8Array subclass, creating buffers, encodings (utf8, hex, base64, latin1), byte vs string length, reading and writing numbers with endianness, shared-memory slices, concatenation and split characters.
kvi5hnuCode Sprout team member6 min readOn this page
Files, network sockets, images, compressed data and cryptographic hashes are all bytes, not text. Node represents a sequence of bytes with the Buffer class. Node invented Buffer before JavaScript had typed arrays; today Buffer is a subclass of Uint8Array (article 79) that adds conversion to and from strings in many encodings, plus methods for reading and writing numbers. Whenever a Node API reads data without being told an encoding, such as fs.readFile(path) or a socket's data event, you get Buffers.
Creating buffers and converting to strings
A character encoding maps characters to bytes. Buffer.from(string, encoding) encodes text into bytes, and buffer.toString(encoding) decodes bytes back into text. UTF-8 is the default for both:
const word = Buffer.from("café ☕", "utf8");
console.log(word);
console.log(word.length, "bytes for", "café ☕".length, "UTF-16 code units");
console.log(word.toString("hex"));
console.log(word.toString("base64"), "|", word.toString("base64url"));
console.log(Buffer.from("Y2Fmw6kg4piV", "base64").toString());
// Buffers are mutable byte arrays (a subclass of Uint8Array)
const code = Buffer.from("HAL", "ascii");
for (let i = 0; i < code.length; i++) code[i] += 1;
console.log(code.toString("ascii"), code instanceof Uint8Array);
console.log(Buffer.alloc(4), Buffer.alloc(6, "ab"), Buffer.alloc(3, 0xff));
console.log(Buffer.byteLength("☕"), Buffer.byteLength("☕", "utf16le"));
<Buffer 63 61 66 c3 a9 20 e2 98 95>
9 bytes for 6 UTF-16 code units
636166c3a920e29895
Y2Fmw6kg4piV | Y2Fmw6kg4piV
café ☕
IBM true
<Buffer 00 00 00 00> <Buffer 61 62 61 62 61 62> <Buffer ff ff ff>
3 2
Things to notice:
- Node prints Buffers as hexadecimal bytes.
"é"takes 2 bytes in UTF-8 and"☕"takes 3, so the byte length (9) differs from the string length (6). UseBuffer.byteLength(text)when you need the size in bytes, for example for aContent-Lengthheader or a database column limit.- Buffers are mutable, and indexing gives single bytes (numbers 0–255).
The supported encodings:
| Encoding | Use |
|---|---|
"utf8" (default) | text; all of Unicode, 1 to 4 bytes per character |
"utf16le" (alias "ucs2") | 2 or 4 bytes per character, the way JavaScript strings are stored internally |
"latin1" (alias "binary") | one byte per character, for ISO-8859-1 text |
"ascii" | 7-bit ASCII only |
"hex" | two hex digits per byte: hashes, debugging |
"base64" / "base64url" | 4 characters per 3 bytes, for putting binary data in text: email, JSON, data URLs, JWTs (base64url is URL-safe) |
Ways to create buffers:
Buffer.from(string, encoding),Buffer.from(arrayOfBytes),Buffer.from(arrayBuffer, offset, length)(shares that memory) andBuffer.from(otherBuffer)(copies).Buffer.alloc(size, fill?)creates a zero-filled buffer, or one filled with a repeating value.Buffer.allocUnsafe(size)is faster because it skips zero-filling, but the memory may contain old data from elsewhere in the process. Only use it when you'll overwrite every byte immediately; never send an unsafe buffer anywhere before filling it.
Reading and writing numbers
Binary file formats and network protocols store numbers as fixed-size fields. Buffer methods read and write them at a byte offset, with the size and type in the name: readUInt8, readInt16BE, readUInt32LE, readFloatBE, readDoubleLE, readBigUInt64BE and the matching write... methods.
Numbers wider than one byte also need a byte order: BE (big-endian) puts the most significant byte first, the convention for network protocols; LE (little-endian) puts it last, which is how x86 and ARM processors store numbers. The reader and writer must agree:

// A tiny binary record: magic "TEA1", version (uint8), count (uint16 BE),
// price (float32 LE) and a signed temperature offset (int8)
const record = Buffer.alloc(12);
let offset = record.write("TEA1", 0, "ascii"); // returns the number of bytes written
offset = record.writeUInt8(2, offset); // each write... returns the next offset
offset = record.writeUInt16BE(1200, offset);
offset = record.writeFloatLE(12.5, offset);
offset = record.writeInt8(-3, offset);
console.log(record, "used", offset, "of", record.length, "bytes");
const parsed = {
magic: record.toString("ascii", 0, 4),
version: record.readUInt8(4),
count: record.readUInt16BE(5),
price: record.readFloatLE(7),
offset: record.readInt8(11),
};
console.log(parsed);
console.log(record.readUInt16LE(5), "<- the same two bytes read in the wrong byte order");
try {
record.readUInt32BE(10);
} catch (err) {
console.log(err.code);
}
<Buffer 54 45 41 31 02 04 b0 00 00 48 41 fd> used 12 of 12 bytes
{ magic: 'TEA1', version: 2, count: 1200, price: 12.5, offset: -3 }
45060 <- the same two bytes read in the wrong byte order
ERR_OUT_OF_RANGE
Each write... method returns the offset just after what it wrote, which makes sequential writing easy. Reading or writing past the end throws a RangeError with code ERR_OUT_OF_RANGE. -3 is stored as fd because signed integers use two's complement. For arbitrary layouts, a DataView over the buffer's memory works too (article 79).
Slicing, copying and combining
const original = Buffer.from("hello world");
const view = original.subarray(0, 5); // shares memory with original
const copy = Buffer.from(original.subarray(0, 5)); // independent bytes
view[0] = 0x4a; // "J"
console.log(original.toString(), "|", view.toString(), "|", copy.toString());
const joined = Buffer.concat([Buffer.from("tea "), Buffer.from("time")]);
console.log(joined.toString(), joined.length);
console.log(Buffer.from("abc").equals(Buffer.from("abc")), Buffer.compare(Buffer.from("a"), Buffer.from("b")));
console.log(joined.indexOf("time"), joined.includes("tea"));
// A multi-byte character split across two chunks
const bytes = Buffer.from("☕");
const first = bytes.subarray(0, 2), second = bytes.subarray(2);
console.log(JSON.stringify(first.toString() + second.toString()));
const { StringDecoder } = require("node:string_decoder");
const decoder = new StringDecoder("utf8");
console.log(JSON.stringify(decoder.write(first) + decoder.write(second)));
// Converting between Buffer and plain Uint8Array / ArrayBuffer
const u8 = new Uint8Array([104, 105]);
console.log(Buffer.from(u8.buffer, u8.byteOffset, u8.byteLength).toString(), new TextDecoder().decode(u8));
Jello world | Jello | hello
tea time 8
true -1
4 true
"��"
"☕"
hi hi
subarray(start, end)creates a view of the same memory: changing the view changes the original, which is efficient but surprising. (buffer.slice()behaves the same way on Buffers, unlikesliceon ordinary typed arrays, and is deprecated for that reason.) Wrap it inBuffer.from()when you need an independent copy.Buffer.concat(list)joins buffers, the usual way to assemble data received in chunks.equals,compare,indexOfandincludessearch and compare bytes. (To compare secrets like tokens or signatures, usecrypto.timingSafeEqual, which takes the same time whatever the input.)- A multi-byte character can be split between two chunks. Decoding each chunk separately produces replacement characters (
�). AStringDecoder, orTextDecoderwith{ stream: true }(article 117), holds incomplete bytes until the rest arrives. Streams do this automatically when you callsetEncoding("utf8")(article 126).
Because a Buffer is a Uint8Array, you can pass it anywhere a Uint8Array is expected: TextDecoder, crypto.subtle, fetch bodies, WebAssembly memory. Going the other way, Buffer.from(u8.buffer, u8.byteOffset, u8.byteLength) wraps an existing typed array without copying. In code meant to run in both Node and browsers, prefer plain Uint8Array with TextEncoder/TextDecoder, and use the newer Uint8Array base64 and hex methods (ES2026) where supported.
Common questions
Why is the file I read printing as <Buffer ...>?
Without an encoding, fs.readFile returns raw bytes. Pass "utf8" (readFile(path, "utf8")) to get a string, or call buffer.toString().
Why does my text get corrupted when I join chunks with +=?
text += chunk decodes each chunk separately, so a multi-byte character split across chunks is broken. Collect the Buffers and decode once with Buffer.concat(chunks).toString(), or use a StringDecoder/setEncoding("utf8").
Is Buffer.allocUnsafe dangerous?
It can leak old memory contents if you send or store the buffer before overwriting every byte. Use Buffer.alloc unless profiling shows the zero-filling matters.
Summary
Bufferis Node's byte array, aUint8Arraysubclass with string encoding and number reading support.- Convert with
Buffer.from(text, encoding)andbuf.toString(encoding); encodings include utf8, utf16le, latin1, ascii, hex, base64 and base64url. Byte length is not string length. read/writemethods handle integers and floats of each size and signedness, in big- or little-endian order, at explicit offsets.subarrayshares memory;Buffer.from(buf)copies;Buffer.concatjoins;StringDecoderhandles characters split across chunks.
Practice Questions
What does Buffer.from("€").length return, and why isn't it 1?
Answer
3. The euro sign takes three bytes in UTF-8, the default encoding. "€".length is 1 because it counts UTF-16 code units, not bytes.
Write code that stores the number 258 as a big-endian unsigned 16-bit value and prints the bytes in hex.
Answer
const b = Buffer.alloc(2);
b.writeUInt16BE(258);
console.log(b.toString("hex")); // "0102"
258 is 0x0102: the high byte 01 comes first in big-endian order.
After const part = data.subarray(0, 4); part.fill(0);, what happened to data?
Answer
Its first four bytes are now zero. subarray returns a view of the same memory, so changes through the view affect the original. Use Buffer.from(data.subarray(0, 4)) to work on a copy.
How do you turn a hex string such as "48656c6c6f" into text?
Answer
Buffer.from("48656c6c6f", "hex").toString() returns "Hello".
Previous: Asynchronous Node: Callbacks, Promises, Sync APIs and the Event Loop Phases
Next: Node Events: EventEmitter, Listeners, Errors and Async Event Helpers

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.