Buffer, bytes, encodings, and ArrayBuffer

Convert between text and bytes and understand how Buffer relates to ArrayBuffer.

🎯 Introduction

By the end of this article, you will be able to convert between text and bytes and understand how Buffer relates to ArrayBuffer.


🧱 Buffer stores bytes; encodings interpret text

A Buffer is a Node.js object that holds bytes. A byte is a basic unit of file and network data and can represent an integer from 0 to 255. Images, text, and compressed files can all be stored as bytes, but not all bytes should be read as text.

A character encoding defines how text maps to bytes. UTF-8, for example, represents a Chinese character with multiple bytes and uses the same rules to decode them. In one .mjs file, first create a Buffer, decode it, and inspect its length. Run the later copying and sharing examples separately. No packages are required.


📝 from: convert text to a Buffer

const bytes = Buffer.from('你好', 'utf8')
console.log(bytes)

This prints <Buffer e4 bd a0 e5 a5 bd>. from returns a new Buffer. Each of the six hexadecimal groups represents a byte; the display is not garbled text.

Image reads and network operations often produce objects like this. Determine what the data represents before deciding whether to convert it to a string.


📖 toString: decode text with an encoding

Append this to the previous code:

console.log(bytes.toString('utf8'))

The additional output is 你好, a regular JavaScript string. toString returns the conversion result without turning the original Buffer into a string. Mismatched decoding rules may produce garbled text or replacement characters.


📏 length counts bytes here

Continue by inspecting the same Buffer:

console.log(bytes.length)

This prints 6, whereas '你好'.length is 2. They count different things: Buffer counts bytes, while JavaScript strings count UTF-16 code units. Each of these two Chinese characters occupies one such unit.

Do not substitute string length for byte length when calculating file sizes or request body lengths. The difference is especially noticeable with Chinese characters and emoji.


⚖️ Copy a Buffer without changing the original

When Buffer.from receives an existing Buffer, it copies the contents. Run this example separately:

const original = Buffer.from('A')
const copy = Buffer.from(original)
copy[0] = 66
console.log(original.toString(), copy.toString())

This prints A B. The encoding value of A is 65 and that of B is 66. Changing the copy's byte leaves the original unchanged. Use this when data needs independent modification.


🔗 How ArrayBuffer, Uint8Array, and Buffer work together

ArrayBuffer stores bytes, Uint8Array lets you read and write individual bytes, and Buffer adds common Node.js byte operations and encoding conversions. For example, if an API returns an ArrayBuffer containing text, Buffer can decode it.

ArrayBuffer: allocate storage first

ArrayBuffer is JavaScript's binary storage object. It represents a region of memory, but does not itself provide indexed byte access or methods for converting bytes to text.

Create a separate binary.mjs and append the following examples in order:

const memory = new ArrayBuffer(2)
console.log(memory.byteLength)

This prints 2. It allocates two bytes, both initially 0. The 2 counts bytes, not string elements; an ArrayBuffer is not a regular array.

Uint8Array: read and modify individual bytes

Uint8Array is a typed array: each element uses a specified numeric type. Uint8 means an unsigned 8-bit integer. Each element occupies one byte and represents values from 0 to 255.

Pass the existing ArrayBuffer to access its storage:

const bytes = new Uint8Array(memory)
bytes[0] = 65
bytes[1] = 66
console.log(bytes)

This prints Uint8Array(2) [65, 66]. No data is copied: the two bytes in memory are modified. An object that accesses existing storage in this way is called a view. This does not mean a web page view or a conversion to a separate copy.

Buffer: decode the same bytes as text

In Node.js, pass this ArrayBuffer to Buffer:

const buffer = Buffer.from(memory)
console.log(buffer.toString('utf8'))

This prints AB because UTF-8 bytes 65 and 66 represent A and B. Buffer supports indexed byte access and adds encoding methods such as toString('utf8').

The objects now have these roles:

ObjectRole in this example
memory (ArrayBuffer)Stores two bytes
bytes (Uint8Array)Reads and writes those bytes by index
buffer (Buffer)Accesses the same bytes and decodes them as text

Shared data: changes are visible through both views

Modify the Uint8Array again:

bytes[0] = 67
console.log(buffer.toString('utf8'))

This prints CB. Uint8Array and Buffer use the same storage, so changes are immediately visible through both. Unlike Buffer.from(existingBuffer), which copies data, passing an ArrayBuffer shares its data.

When Node.js file APIs return a Buffer, use it directly. Consider this conversion when integrating APIs that return ArrayBuffer; there is no need to create all three objects manually to read an ordinary file.


🪤 Base64 is a representation, not encryption

Encode bytes as Base64 when they need to pass through text fields:

console.log(Buffer.from('hello').toString('base64'))

This prints aGVsbG8=. To decode it, specify base64 as the input encoding:

console.log(Buffer.from('aGVsbG8=', 'base64').toString('utf8'))

This prints hello.

Anyone with the content can decode it using the same rules, so it cannot keep data secret. Chunked text has another issue: a Chinese character may span two chunks, and decoding each independently may break it. The streams chapter explains how to handle this.


❓ Questions and answers

Q1: Why does reading text return a Buffer?

File APIs generally return raw bytes when no encoding is specified. Specify one or call toString.

Q2: Can Base64 hide sensitive content?

No. It is only a reversible encoding.

Q3: Does Buffer.from(existingBuffer) share data?

This overload copies the content, unlike passing an ArrayBuffer, which shares storage.


🧪 Exercise

Convert hello and 你好 to Buffers, print their byte lengths, then decode them back to text.

// Write your code here

🎉 Try these techniques with your own examples!