CodePark/ questions / Buffers & binary data
START PRACTICINGPRACTICE
Backend question · Node.js › Buffers & binary data

What is a Buffer in Node.js, and why does Node need it?

A Buffer is a fixed-length sequence of raw bytes. It is a subclass of Uint8Array, so it works with typed array APIs. Its memory lives outside the V8 heap (the memory area for normal JavaScript objects).

Why Node needs it: JavaScript strings are sequences of UTF-16 code units. That is the wrong shape for files, sockets, images or compressed data. Node needs a raw byte type for this. Buffer existed in Node before JavaScript had typed arrays.

To create a buffer, use one of these:

  • Buffer.from(string, encoding)
  • Buffer.from(array)
  • Buffer.alloc(size)

To convert back to a string, use buf.toString(encoding). Supported encodings include utf8 (the default), base64, base64url, hex, latin1 and ascii. Streams and fs functions return buffers, unless you give them an encoding.

  • A Buffer holds fixed-length raw bytes and is a subclass of Uint8Array.
  • Node needs Buffers for binary data such as files, sockets, crypto and images.
  • Create a Buffer with from or alloc, and convert it with toString(encoding).
  • The default encoding is utf8. Others include base64, hex and latin1.