Buffer.from()

Creates a Buffer from a string, an array of bytes, an ArrayBuffer or another Buffer.

Signature
Buffer.from(string[, encoding])
  • Added in Node.js v5.10.0

Parameters

ParameterTypeDescription
$stringstringA string to encode.
$encodingoptionalstring= 'utf8'The encoding of string.

Return value

BufferA new Buffer containing the encoded string. The other overloads return a Buffer built from an array of byte values, a view onto an ArrayBuffer, or a copy of an existing Buffer.

Errors

Throws TypeError (ERR_INVALID_ARG_TYPE) if the first argument is not a string, array-like value, ArrayBuffer, Buffer, or an object with valueOf() or Symbol.toPrimitive.

Changelog

  • PHP v8.2.0Added the Buffer.from(object[, offsetOrEncoding[, length]]) overload, which accepts any object exposing valueOf() or Symbol.toPrimitive.
  • PHP v6.0.0Buffer.from() was introduced as the safe replacement for the new Buffer() constructor, which is deprecated.

Buffer.from() is how binary data enters your program. It is a family of overloads, and picking the wrong one is the usual source of surprise.

The overloads

SignatureWhat it does
Buffer.from(string[, encoding])Encodes text into bytes using encoding (default 'utf8'). Also how you decode 'hex' and 'base64' input.
Buffer.from(array)Copies an array of numbers, each masked to 0–255.
Buffer.from(buffer)Copies an existing Buffer or Uint8Array.
Buffer.from(arrayBuffer[, byteOffset[, length]])Shares the memory of an ArrayBuffer. No copy is made.
Buffer.from(object[, offsetOrEncoding[, length]])Uses the object's valueOf() or Symbol.toPrimitive.

Copy or view?

Handed a Uint8Array, Buffer.from(typedArray) copies the bytes; Buffer.from(typedArray.buffer) creates a view over the same memory, so later writes on either side are visible through the other — and it ignores the typed array's own byteOffset and length, giving you the whole underlying buffer unless you pass them yourself.

Reach for it when decoding base64 or hex, when turning a request body into bytes, and whenever old code calls new Buffer(), which is deprecated because it silently changed meaning depending on the argument type.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Decode a base64 or hex string from a JSON payload back into raw bytes.
  • Turn a request body string into bytes so you can measure or hash it.
  • Wrap a Uint8Array coming from a Web API in a Buffer to use Node's encodings.
  • Replace deprecated new Buffer() calls in legacy code.

Frequently asked questions

What replaced new Buffer() in Node.js?

Buffer.from() replaced new Buffer() for existing data, and Buffer.alloc() replaced it for new empty buffers. new Buffer() is deprecated because it treated a number as a size and anything else as content, so an attacker-controlled value could hand you uninitialised memory.

Does Buffer.from copy the data?

It copies for strings, arrays, Buffers and TypedArrays, but not for an ArrayBuffer or SharedArrayBuffer, where it creates a view sharing the same memory. Use Buffer.from(new Uint8Array(arrayBuffer)) if you need an independent copy.

How do I convert a string to a Buffer with a specific encoding?

Pass the encoding as the second argument, as in Buffer.from(text, 'latin1'). Supported encodings include utf8, utf16le, latin1, base64, base64url, hex and ascii; an unknown name throws ERR_UNKNOWN_ENCODING.

More examples

Decoding hex and base64

The second argument is the encoding of the input, not of the output. Node's base64 decoder is lenient: it ignores characters outside the alphabet and tolerates missing padding, so a corrupted token decodes to garbage instead of raising an error. Validate the input yourself if that matters.

Example · javascript
const hex = Buffer.from('deadbeef', 'hex');
console.log(hex.length, hex[0]);            // 4 222

const decoded = Buffer.from('SGVsbG8=', 'base64');
console.log(decoded.toString('utf8'));      // Hello

// base64url is accepted too, and padding is optional.
console.log(Buffer.from('YT9iPmM', 'base64url').toString());  // a?b>c

// Invalid characters are skipped rather than throwing.
console.log(Buffer.from('!!SGVsbG8=!!', 'base64').toString()); // Hello

Windowing an ArrayBuffer without copying

byteOffset and length carve a view out of a larger allocation, which is how you parse a big received block without allocating per field. Writing through the view mutates the ArrayBuffer everything else sees; the Uint8Array overload on the last two lines copies instead, so the parent is untouched.

Example · javascript
const backing = new ArrayBuffer(8);
new Uint8Array(backing).set([1, 2, 3, 4, 5, 6, 7, 8]);

// Expose only bytes 2..5 of the backing store.
const window = Buffer.from(backing, 2, 4);
console.log(window.length, [...window]);   // 4 [ 3, 4, 5, 6 ]

window[0] = 99;
console.log(new Uint8Array(backing)[2]);   // 99 - the parent changed

// Compare with the copying overload:
const independent = Buffer.from(new Uint8Array(backing, 2, 4));
independent[0] = 0;
console.log(new Uint8Array(backing)[2]);   // still 99

Restoring a Buffer that travelled through JSON

JSON.parse hands back a plain object with a data array, never a Buffer. Feeding that array to Buffer.from rebuilds the bytes exactly, which is the standard fix when a Buffer crosses an HTTP or message-queue boundary as JSON.

Example · javascript
const original = Buffer.from('secret');
const wire = JSON.stringify({ token: original });
// '{"token":{"type":"Buffer","data":[115,101,99,114,101,116]}}'

const parsed = JSON.parse(wire);
console.log(Buffer.isBuffer(parsed.token));        // false

const restored = Buffer.from(parsed.token.data);   // the array overload
console.log(restored.toString());                  // secret
console.log(restored.equals(original));            // true

Discussion

  • Be the first to comment on this lesson.