JavaScript ArrayBuffer vs Buffer

When JavaScript code handles bytes, choosing between ArrayBuffer and Buffer affects how those bytes are accessed and passed on. ArrayBuffer stores raw bytes for typed views, while Buffer is Node.js’s Uint8Array subclass with byte and encoding methods.

This article compares their uses and shows how to convert between them while keeping the intended byte range and choosing whether to share or copy.

TL;DR

Choose Buffer for Node.js byte-oriented APIs, and use ArrayBuffer with a typed view when code must work with browser APIs or needs a specific numeric view.

  • ArrayBuffer holds raw bytes. Uint8Array and DataView provide access.
  • Buffer is Node.js’s Uint8Array subclass with extra byte and encoding methods.
  • Buffer.from(arrayBuffer, offset, length) shares bytes. Buffer.from(buffer) copies them.

What Is an ArrayBuffer?

An ArrayBuffer stores bytes, and its byteLength reports the current size of that backing store.

When created as resizable, an ArrayBuffer can grow only up to its configured maxByteLength. A library that accepts buffers from several runtimes should check support before relying on that option.

An ArrayBuffer does not expose numeric indexing by itself. A view supplies that access and defines how the same bytes are interpreted. Uint8Array reads each byte as an integer from 0 through 255, while a wider typed array groups adjacent bytes into numeric elements.

The distinction matters when an API returns storage but leaves the format to the caller. A four-byte region might represent four independent values, one 32-bit integer, or part of a text encoding. The storage type alone cannot tell the parser which meaning is correct.

ArrayBuffer.prototype.slice(start, end) creates a new buffer containing a selected byte range. This is useful when the consumer should own a snapshot rather than read later changes to the original storage.

A worker transfer changes which context owns the bytes, and the sender’s former buffer becomes detached.

The receiving code should validate the message structure after handoff because transfer does not check whether bytes match the expected format.

Buffer vs ArrayBuffer: The Practical Differences

Buffer is Node.js’s byte-oriented class and includes methods for text encoding, integer reads and writes. Browser code generally uses ArrayBuffer with a typed view instead.

QuestionBufferArrayBuffer
Where available?Node.js; not a browser built-inJavaScript runtimes and browser APIs
How do you access bytes?Direct byte indexing and Buffer methodsThrough Uint8Array, another typed array, or DataView
Common Node.js input?File reads and many Node APIs return or accept BufferUseful at Web API and cross-runtime boundaries
Conversion behavior?Depends on Buffer.from input typeA backing store that views may share

View construction is also a choice about lifetime. A small view can keep a larger backing allocation reachable as long as the view remains in use, so copy a small retained fragment when keeping the whole input alive would be undesirable.

With a multi-byte typed array, Buffer.from(typedArray) copies its numeric elements as one byte each. Buffer.from(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength) instead views the stored representation, whose byte order is native to the platform.

For a packet with a text field, identify its byte boundaries before decoding so binary headers and checksums stay out of the resulting string.

Byte order becomes visible when a value spans multiple bytes. A network format may specify big-endian order, while another file format specifies little-endian order. DataView read methods accept a boolean for that choice on multi-byte values, so the parser can follow the format rather than assume the host’s native order.

Typed arrays use the platform’s native byte order. They suit data whose elements follow that representation, such as a numeric sample array. For a portable file field with a defined order, DataView makes the choice explicit at the read site and helps reviewers compare code with the format specification.

For a Node.js file workflow, file APIs provide bytes as Buffer when no text encoding is requested. Keep binary file data in that byte representation during processing.

Node.js HTTP IncomingMessage is a readable stream, so request data arrives in chunks. Process those chunks incrementally when the format permits. Collect them into one Buffer only when the complete body is required and the application has an input-size limit.

How Typed Arrays and DataView Work

Typed arrays represent uniform-width elements in native byte order, while DataView handles mixed-width fields and explicit byte-order reads.

ViewElement sizeUseful forIndex unit
Uint8Array1 byteRaw bytes, file chunks and encoded textByte
Int16Array2 bytesSigned 16-bit numeric samples16-bit element
Float32Array4 bytes32-bit floating-point values32-bit element
DataViewChosen per operationFormat fields with different numeric widthsByte offset

Use the offset and length that belong to the intended view. A DataView can read a multi-byte field beginning at byte 1, provided the full field remains inside the view.

  • Use ArrayBuffer.isView(value) to test for a typed-array or DataView object. A raw ArrayBuffer is not itself a view.

TypedArray slice creates a copy of its selected elements, while subarray creates another view over the same storage. Buffer preserves a legacy slice method that acts as a view, so subarray is clearer when code wants shared bytes across both Buffer and typed-array values.

ArrayBuffer in Web APIs

Use Response.arrayBuffer() when the parser needs the whole resource before it can interpret the data.

  • Response.arrayBuffer() reads the Fetch body to completion. Check response.ok first, and account for a disturbed or locked body, which makes the read reject.
  • File and Blob objects expose arrayBuffer() so a selected image or document can be passed to a typed view or format parser.

The returned value contains the response body bytes after the body has been consumed. Check the status before parsing because a completed error response can still contain bytes, but those bytes may describe a server error rather than the requested file.

For a large response, a streaming reader can process chunks as they arrive and avoid holding the entire body at once. That choice requires the parser to handle boundaries between chunks. A length-prefixed record or encoded character can be split across reads, so retain enough state to finish it safely.

Which Representation Fits the Task?

No single byte type fits every runtime. Choose the type the receiving API documents.

WorkRepresentation to start withReason
Node.js file or socket dataBufferNode APIs commonly return or accept Buffer values
Browser response bodyArrayBuffer with Uint8Array or DataViewBrowser APIs expose standard binary storage and views
Mixed-width binary recordArrayBuffer with DataViewReads can specify byte offsets, numeric widths and byte order
Cross-runtime byte processingUint8ArrayNode Buffer inherits from Uint8Array and browsers provide the same typed view

Benchmark the Workload You Run

There is no universal speed winner between Buffer and ArrayBuffer operations. Start from a profile and keep the runtime, payload and operation sequence consistent when you benchmark the slow path.

  • Allocation and initialization: record whether setup is part of the measured path.
  • Byte reads and writes: isolate the transformations that dominate the application.
  • Encoding, parsing and I/O: include the boundaries used by production code.
  • Representative payloads under concurrency: compare latency and throughput at the expected load.

Record the host, runtime and payload alongside each result so another developer can reproduce the same test conditions.

Convert Buffer and ArrayBuffer Safely

Node.js provides Buffer.from overloads for byte input, Buffer values and ArrayBuffer storage.

Step 1: Identify the Input Range

Check whether the source is a complete backing store or a view over only part of one before you convert it.

Step 2: Create the Node.js View or Copy

Buffer.from(arrayBuffer, byteOffset, byteLength) shares that range, while Buffer.from(existingBuffer) copies the Buffer’s visible bytes. In the example, the view mutation appears through both references and the copy mutation leaves the source unchanged.

const { Buffer } = require('node:buffer');

const backing = new ArrayBuffer(8);
const bytes = new Uint8Array(backing, 2, 3);
bytes.set([65, 66, 67]);
const view = Buffer.from(backing, bytes.byteOffset, bytes.byteLength);
console.log('view:', view.toString('ascii'));
view[0] = 88;
console.log('shared byte:', bytes[0]);

const copy = Buffer.from(view);
copy[1] = 89;
console.log('source after copy:', view.toString('ascii'));
console.log('copy:', copy.toString('ascii'));

try {
  Buffer.from(null);
} catch (error) {
  console.log('bad input:', error.name);
}

The program prints these exact lines:

view: ABC
shared byte: 88
source after copy: XBC
copy: XYC
bad input: TypeError

The shared byte is 88, the character code for X.

Afterward the sample copies the Buffer’s visible bytes. Changing the second byte in the copy produces XYC, while the original remains XBC, which is the behavior to choose for independent ownership.

Step 3: Make a Standalone ArrayBuffer

When the receiver specifically requires an ArrayBuffer, copy the Buffer into a new Uint8Array and pass that new view’s buffer. APIs that accept typed views can receive the Uint8Array directly.

Step 4: Encode or Decode Text Deliberately

In Node.js, Buffer.from(text, ‘utf8’) encodes text, while Buffer.toString(‘utf8’) decodes UTF-8 bytes. Browser code can use TextEncoder.encode for a Uint8Array and TextDecoder to decode a byte view. Image and compressed data should remain binary rather than being interpreted as text.

Step 5: Preserve UTF-8 State Across Chunks

Node.js StringDecoder retains an incomplete UTF-8 sequence between writes and handles any remainder when end() is called. Keep one decoder for each independent stream.

Hexadecimal and Base64 are encodings for representing bytes as text, not substitutes for UTF-8 decoding. Buffer can encode bytes to either form for transport or logs, then convert them back to bytes with the matching encoding label.

When a text conversion looks corrupted, check the input encoding, the byte boundaries and whether a multi-byte character was split across chunks. Those checks address separate failure causes, so confirm them in that order rather than changing the bytes blindly.

The Node.js StringDecoder documentation explains the chunk-boundary behavior, while MDN’s TextDecoder reference covers decoding typed-array input in browser code.

I ran the demo file with Node.js v26.7.0. It shows the two conversion contracts directly, and the final line also records the unsupported-input case.

Terminal output showing a Buffer view sharing bytes with an ArrayBuffer and Buffer copy behavior
Node.js output showing shared-view mutation and an independent Buffer copy.

Byte Ranges, Copies, and Other Edge Cases

Conversion bugs usually come from mismatched assumptions about byte ranges, input types or ownership.

CaseWhat happensSafer choice
Need an independent BufferA shared view can reflect later writesUse Buffer.from(bufferView) to copy the visible bytes
Buffer.from(null)Node.js throws TypeError with ERR_INVALID_ARG_TYPEPass a supported value such as a string, byte array or ArrayBuffer
Decode UTF-8 bytesInput bytes encode characters using a chosen formatUse buf.toString(‘utf8’) or TextDecoder

In the run above, Buffer.from(null) raised TypeError with code ERR_INVALID_ARG_TYPE. Pass a byte sequence or a supported container such as an ArrayBuffer or string.

Buffer.alloc zero-fills its allocation. Buffer.allocUnsafe does not initialize its bytes, so calculate the output size and write every byte before reading or exposing that value.

Conclusion

Confirm call signatures and runtime support in the documentation for the API that consumes the bytes.

For the authoritative behavior, consult the Node.js Buffer documentation, especially its Buffer and TypedArray section, and MDN’s ArrayBuffer reference. CodeForGeek’s Node.js StringDecoder guide covers incremental text decoding, while writing files in Node.js shows another common boundary where byte data meets filesystem APIs.

FAQ

These answers address common questions about the two byte representations.

What is an ArrayBuffer in JavaScript?

An ArrayBuffer is a backing store for raw binary bytes. Use a typed array or DataView to read and write its contents.

Does Buffer.from(arrayBuffer) copy the bytes?

No. Buffer.from(arrayBuffer, byteOffset, length) creates a Buffer view over the specified range and shares the ArrayBuffer memory.

How do I avoid including extra bytes when converting a Buffer?

Use the Buffer’s backing buffer together with its byteOffset and byteLength. Passing only buffer.buffer can include bytes outside the Buffer view.

How can I convert ArrayBuffer bytes to text?

Create a Uint8Array view and decode it with TextDecoder, or use Buffer.from(arrayBuffer).toString(‘utf8’) in Node.js when the bytes are UTF-8 text.

Ninad Pathak
Ninad Pathak

Ninad Pathak is a founding member and Editor in Chief at CodeForGeek. He writes about practical AI tooling and developer workflows, and outside work you will likely find him with a book, hot brewed coffee, and ambient music.

Articles: 80