Buffer creation and encoding
Local practice: Node.js 22.16.0 and npm 10.9.2 on Linux x64; proposed teaching baseline 26.13.1 LTS remains untested. Use a fresh disposable folder for each example, copy only the shown files and run the fixed command. No packages or external services required. Static examples are not ByteMind runner support. The archive is author-only; do not copy expected.json into the example directory.
Measure text and bytes
import { Buffer } from "node:buffer";const text = "café";const bytes = Buffer.from(text, "utf8");console.log(text.length, bytes.length, Buffer.byteLength(text, "utf8"));console.log(bytes.toString("hex"));Run in this fixture directory:
node main.mjsExpected stdout:
4 5 5636166c3a9Expected exit status: 0. Expected stderr: empty. The é character occupies two UTF-8 bytes but one UTF-16 code unit in this example.
How it works
Buffer.from(string, encoding) encodes text, Buffer.alloc(size) creates initialized storage, and buf.toString(encoding) decodes or represents bytes. Buffer.byteLength(text, "utf8") gives encoded byte count rather than JavaScript UTF-16 code-unit count. Hex represents each byte with two digits; Base64 represents bytes with a text alphabet and is not encryption. A Buffer is a Uint8Array subclass. Buffer.from has multiple overloads: passing a Buffer copies its bytes, while passing an ArrayBuffer can share storage. Prefer initialized allocation for beginner examples; uninitialized allocation requires complete overwrite before use.
Allocate initialized bytes and round-trip Base64
import { Buffer } from "node:buffer";const bytes = Buffer.alloc(3);bytes[0] = 65;bytes[1] = 66;bytes[2] = 67;const encoded = bytes.toString("base64");console.log(encoded, Buffer.from(encoded, "base64").toString("utf8"));console.log(Buffer.alloc(0).length);Run in this fixture directory:
node main.mjsExpected stdout:
QUJD ABC0Expected exit status: 0. Expected stderr: empty. The three ASCII byte values encode to ABC; Base64 is reversible without a key.
Common mistake
Do not use string.length to enforce byte-sized protocol limits. Also do not trust a successful Base64 or hex decode as validation of arbitrary input; Node accepts some noncanonical encodings and may truncate invalid hex.
Try it yourself
Encode the string café in UTF-8 and report both its JavaScript length and byte count. Round-trip it via hex, and predict what happens with an empty string.
Further reading: Official documentation 1. Related ByteMind reference candidate: node-buffer-from (route not verified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Buffer creation and encoding — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
How many UTF-8 bytes encode café?
Which API creates zero-filled storage by default?
Is Base64 encryption?