Binary I/O
Representing binary payloads in streams, files, and network protocols.
Node.js · Module
The node:buffer module provides Buffer, Node.js’s fixed-length byte sequence for handling binary data. It extends Uint8Array and supports safe allocation, conversion, encoding, and byte-level operations.
The module provides Buffer, a fixed-size byte sequence represented as a Uint8Array subclass. Create buffers from strings, arrays, ArrayBuffers, or other buffers, then use its methods to inspect, transform, encode, decode, and compare binary data.
import { Buffer } from 'node:buffer';| Name | Type | Description |
|---|---|---|
value | string | ArrayLike<number> | ArrayBuffer | Buffer | Input data such as a string, array, ArrayBuffer, or existing Buffer, depending on the factory used. |
size | integer | Number of bytes for allocation methods. |
encoding | string | Text encoding used when converting strings to or from bytes. |
Buffer instances containing copied data, initialized allocated bytes, or a view over ArrayBuffer memory, depending on the API used.
import { Buffer } from 'node:buffer';
const input = 'hello';
const encoded = Buffer.from(input, 'utf8');
console.log(encoded.length);
console.log(encoded.toString('base64'));Creates a byte buffer from UTF-8 text and prints its byte length and Base64 representation.
Representing binary payloads in streams, files, and network protocols.
Converting text or structured byte values to encoded data.
Working with typed-array and ArrayBuffer-based APIs.
Buffer represents a fixed-length sequence of bytes and extends Uint8Array with Node-specific methods. It is used by many Node.js APIs for binary data.
Follow-up: How can text be converted to a Buffer? Use Buffer.from(string, encoding), choosing the encoding explicitly when it is not UTF-8.
Buffer.from() creates a buffer from existing data, while Buffer.alloc() creates a specified-size buffer that is initialized safely. Buffer.allocUnsafe() can be faster but requires the contents to be overwritten or initialized before use.
Follow-up: When is allocUnsafe acceptable? Only when every byte will be deliberately initialized before the buffer can be observed.
Buffer.from(buffer) copies the source buffer's contents into a new Buffer. Buffer.from(arrayBuffer) instead creates a Buffer that shares the ArrayBuffer's memory, optionally using an offset and length.
Follow-up: What consequence follows from shared memory? Changes through either view can affect the same underlying bytes, so ownership must be managed carefully.
Buffer.from()Buffer.alloc()Buffer.allocUnsafe()buf.toString()Uint8Arraybuffer.constants