Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Libraries: data & formats

Structured and binary data: JSON and config formats, bytes, encodings, regular expressions, hashing and cryptography, compression, SQL databases, URLs and templates. Entries outside the standard library name what to install.

TypeScript docs Node.js API index ↗

JSON: JSON, encoding/json, serde_json, nlohmann/json

TypeScript

JSON is a built-in global with two functions: JSON.parse turns text into plain values and JSON.stringify turns values into text, with optional indentation. Parsing does not check the result against a TypeScript type; the type is an assumption you make, so validate untrusted input by hand or with a schema library such as Zod. Dates become strings and undefined fields are dropped.

Complete program

Complete program. Built in: globals need no import; node: modules ship with Node.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Order = { id: number; items: string[] };

const text = '{"id": 7, "items": ["bolt", "nut"]}';
const value: unknown = JSON.parse(text); // throws SyntaxError on malformed JSON

if (typeof value === 'object' && value !== null && 'id' in value) {
  const order = value as Order; // a cast: nothing is checked at runtime
  console.log(order.id, order.items.length);
}

console.log(JSON.stringify({ id: 8, items: [] }));
console.log(JSON.stringify({ id: 8 }, null, 2)); // pretty-printed

Most used: JSON.parse, JSON.stringify(value, null, 2), response.json() with fetch, a reviver or replacer for custom types.

Zod (4.x, npm install zod) is the common schema library: const User = z.object({ name: z.string(), age: z.number().int() }) describes the shape once, User.parse(JSON.parse(text)) checks it and throws a ZodError with every problem, safeParse returns a result instead of throwing, and type User = z.infer<typeof User> derives the TypeScript type so the two cannot drift.

Valibot and ArkType fill the same role. Validate at the boundary where untrusted text enters (a request body, a file, an environment variable) and pass typed values inward.

Config formats (TOML, YAML, XML, protobuf): yaml, encoding/xml, serde + toml, toml++

TypeScript

Node has no parser for TOML, YAML, XML or protobuf; JSON is the only format built in. The common packages are yaml (YAML 1.2 parse and stringify, with comments kept in its Document API), smol-toml (TOML 1.0 parse and stringify), fast-xml-parser (XMLParser and XMLBuilder) and, for protobuf, @bufbuild/protobuf with code generated by buf, or protobufjs. Like JSON.parse, these return plain values: the TypeScript type you assign is unchecked, so validate the result (Zod or similar) before trusting it.

Complete program

Complete program.

Before you use this

Not built in: npm install yaml

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { parse, parseDocument, stringify } from 'yaml';

type Config = { name: string; port: number; tags: string[]; db: { url: string } };

const text = `
name: orders
port: 8080 # comments are allowed
tags: [api, internal]
db:
  url: postgres://localhost/orders
`;

const config = parse(text) as Config; // plain values; the type is not checked
console.log(config.name, config.port + 1, config.tags, config.db.url);
console.log(typeof parse('debug: no').debug); // YAML 1.2: 'no' is a string

process.stdout.write(stringify({ ...config, port: 9090 })); // back to YAML text

const doc = parseDocument(text); // keeps comments and layout
doc.set('port', 9091);
console.log(String(doc).split('\n').find((line) => line.startsWith('port')));

Most used: parse and stringify from yaml, parseDocument to edit YAML and keep comments, parse and stringify from smol-toml, new XMLParser({ ignoreAttributes: false }).parse, generated fromBinary and toBinary for protobuf messages.

yaml follows YAML 1.2, where yes, no, on and off are strings. YAML 1.1 parsers (PyYAML, older Go and Ruby libraries) read them as booleans, so the same file can mean different things to different tools; quote values that must stay strings.

parse ignores comments and formatting. To change one value in a hand-written file, use parseDocument, doc.set and String(doc) so the rest of the file is kept.

Bytes & binary data: Uint8Array, encoding/binary, Vec<u8>, std::byte

TypeScript

Binary data is a Uint8Array (or another typed array) over an ArrayBuffer. DataView reads and writes multi-byte numbers in an explicit byte order, and TextEncoder and TextDecoder convert between strings and UTF-8 bytes. Node's Buffer is a Uint8Array subclass with extra helpers (concat, from, toString('hex'), readUInt32BE), and it is what Node's file and network APIs return.

Complete program

Complete program. Built in: globals need no import; node: modules ship with Node.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { Buffer } from 'node:buffer';

const bytes = new TextEncoder().encode('héllo'); // Uint8Array of UTF-8 bytes
console.log(bytes.length, bytes[1].toString(16)); // 6 c3

const header = new Uint8Array(8);
const view = new DataView(header.buffer);
view.setUint32(0, 0xcafebabe); // big-endian unless told otherwise
view.setUint16(4, 513, true); // little-endian
console.log([...header].map((b) => b.toString(16).padStart(2, '0')).join(' '));

const buf = Buffer.concat([Buffer.from('id:'), Buffer.from([0x2a])]); // Node's Uint8Array subclass
console.log(buf, buf.readUInt8(3), new TextDecoder().decode(bytes));

Most used: Uint8Array, ArrayBuffer, DataView getUint32/setUint16, TextEncoder, TextDecoder, Buffer.from, Buffer.concat, buf.toString('hex').

Base64, hex & CSV: Buffer, encoding/*, base64/hex/csv crates, OpenSSL

TypeScript

Node's Buffer converts between bytes and base64, base64url and hex with Buffer.from(text, encoding) and buf.toString(encoding); btoa and atob are the web-standard versions but only handle Latin-1 text. There is no CSV parser in Node or the browser: splitting on commas breaks on quoted fields, so real files use a library such as csv-parse or Papa Parse.

Complete program

Complete program. Built in: globals need no import; node: modules ship with Node.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { Buffer } from 'node:buffer';

const raw = Buffer.from('id=7&ok');
console.log(raw.toString('base64'), raw.toString('base64url'), raw.toString('hex'));
console.log(Buffer.from('aWQ9NyZvaw==', 'base64').toString('utf8'));
console.log(btoa('hi'), atob('aGk=')); // web-standard, Latin-1 text only

// No CSV parser is built in. Splitting works only for simple rows without quotes.
const csv = 'name,qty\nbolt,3\nnut,10';
const [header, ...rows] = csv.split('\n').map((line) => line.split(','));
console.log(header, rows.map(([name, qty]) => ({ name, qty: Number(qty) })));

Most used: buf.toString('base64'), Buffer.from(text, 'base64'), 'base64url', 'hex', btoa, atob, encodeURIComponent, csv-parse.

Regular expressions: RegExp, regexp, regex crate, <regex>

TypeScript

RegExp is built in, with literal syntax /pattern/flags. test checks for a match, exec and match return groups (including named groups), matchAll iterates every match of a /g pattern, and replace and split accept patterns. The engine backtracks, so nested quantifiers on untrusted input can be slow.

Complete program

Complete program. Built in: globals need no import; node: modules ship with Node.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const line = 'order=7 total=40.50 status=paid';

const pattern = /(\w+)=([\w.]+)/g; // literal syntax; g finds every match
const fields = Object.fromEntries([...line.matchAll(pattern)].map(([, k, v]) => [k, v]));
console.log(fields);

const amount = /total=(?<amount>\d+\.\d{2})/.exec(line)?.groups?.amount; // named group
console.log(amount, /^order=\d+/.test(line), line.replace(/\d+/g, '#'));

Most used: /pattern/flags, test, exec, match, matchAll, replace and replaceAll, named groups (?<name>...), the g, i, m, s, u and y flags.

Hashing & cryptography: node:crypto, crypto/*, RustCrypto, OpenSSL

TypeScript

node:crypto wraps OpenSSL: createHash (SHA-256 and others) for checksums and content addresses, createHmac for authenticating messages with a shared key (a MAC), randomBytes and randomUUID for secrets, scrypt and pbkdf2 for password hashing, timingSafeEqual for comparing secrets (it throws if the lengths differ, so check length first), and createCipheriv for AES-GCM encryption. Browsers and Node also expose the asynchronous Web Crypto API (crypto.subtle).

Complete program

Complete program. Built in: globals need no import; node: modules ship with Node.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { createHash, createHmac, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';

const digest = createHash('sha256').update('order:7').digest('hex');
console.log(digest.slice(0, 16)); // checksums, cache keys, content addresses

const key = randomBytes(32); // a shared secret key
const signature = createHmac('sha256', key).update('order:7').digest();
const check = createHmac('sha256', key).update('order:7').digest();
console.log(timingSafeEqual(signature, check)); // constant-time comparison

const salt = randomBytes(16); // passwords: a slow, salted key-derivation function
const stored = scryptSync('correct horse', salt, 32);
console.log(timingSafeEqual(stored, scryptSync('correct horse', salt, 32)));

Most used: createHash('sha256').update(data).digest('hex'), createHmac, randomBytes, randomUUID, scrypt, timingSafeEqual, createCipheriv('aes-256-gcm'), crypto.subtle.

Compression & archives: node:zlib, compress/* + archive/*, flate2, zlib

TypeScript

node:zlib compresses and decompresses gzip, deflate and Brotli (and Zstandard in recent Node versions), with *Sync helpers for small data and streams (createGzip, createGunzip) for large files. There is no built-in zip or tar support; adm-zip, yauzl and tar are common packages. CompressionStream and DecompressionStream (gzip and deflate) are globals in both browsers and Node.

Complete program

Complete program. Built in: globals need no import; node: modules ship with Node.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { brotliCompressSync, gunzipSync, gzipSync } from 'node:zlib';

const text = 'order line\n'.repeat(1000);
const gz = gzipSync(text); // .gz format
console.log(text.length, gz.length, brotliCompressSync(text).length);
console.log(gunzipSync(gz).toString('utf8') === text);

// Large files stream instead of loading everything:
// await pipeline(createReadStream('log.txt'), createGzip(), createWriteStream('log.txt.gz'));

Most used: gzipSync, gunzipSync, createGzip with stream.pipeline, brotliCompressSync, inflateSync, CompressionStream in browsers.

SQL databases: node:sqlite, database/sql, rusqlite/sqlx, SQLite C API

TypeScript

Node includes node:sqlite, a synchronous SQLite driver (DatabaseSync, prepare, run, get, all): behind --experimental-sqlite in Node 22.5 to 22.12, available without a flag from 22.13, and still marked experimental. better-sqlite3 is the established SQLite package; other databases use driver packages such as pg for PostgreSQL and mysql2. Always pass values as parameters (? or $1) instead of building SQL strings. Query builders such as Kysely and ORMs such as Prisma sit on top of the drivers.

Complete program

Complete program. Built in without a flag from Node 22.13 (22.5 to 22.12 need --experimental-sqlite).

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { DatabaseSync } from 'node:sqlite';

const db = new DatabaseSync(':memory:'); // or a file path
db.exec('CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE)');

const insert = db.prepare('INSERT INTO items (name) VALUES (?)'); // ? binds values safely
for (const name of ['bolt', 'nut']) insert.run(name);

const rows = db.prepare('SELECT id, name FROM items WHERE name LIKE ?').all('b%');
console.log(rows); // [ { id: 1, name: 'bolt' } ]
db.close();

Most used: new DatabaseSync(path), db.exec, db.prepare(sql).run/get/all, pg Pool.query(sql, params), transactions with BEGIN and COMMIT.

URLs & query strings: URL, net/url, url crate, Boost.URL

TypeScript

URL and URLSearchParams are built-in globals (the WHATWG URL standard, shared with browsers). new URL parses and validates, its properties (hostname, pathname, search, hash) can be read and changed, searchParams handles query strings with correct encoding, and new URL(relative, base) resolves relative references. encodeURIComponent encodes a single component by hand.

Complete program

Complete program. Built in: globals need no import; node: modules ship with Node.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const url = new URL('https://shop.example/orders?status=paid&page=2#top');
console.log(url.hostname, url.pathname, url.searchParams.get('status'));

url.searchParams.set('q', 'bolt & nut'); // encodes the value for you
url.pathname = '/orders/7';
console.log(url.toString());

const base = new URL('https://shop.example/api/');
console.log(new URL('items?id=7', base).href); // resolve a relative reference
console.log(encodeURIComponent('a b/c'), URL.canParse('not a url'));

Most used: new URL(text), url.searchParams.get/set/append, url.pathname, url.href, new URL(path, base), URL.canParse, encodeURIComponent.

Text templates: template literals, text/template, minijinja, std::format

TypeScript

Template literals are the built-in templating: ${expression} interpolates, and map plus join builds repeated sections. They do no escaping, so user text placed into HTML must be escaped first. Larger projects use a template engine (Handlebars, EJS, Nunjucks) or a component framework that escapes by default; tagged templates (a function before the backtick) let a library process the parts.

Complete program

Complete program. Built in: globals need no import; node: modules ship with Node.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Order = { id: number; items: { name: string; qty: number }[] };

const escapeHtml = (text: string) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);

function render(order: Order): string {
  const rows = order.items
    .map((item) => `  <li>${escapeHtml(item.name)} × ${item.qty}</li>`)
    .join('\n');
  return `<h1>Order ${order.id}</h1>\n<ul>\n${rows}\n</ul>`;
}

console.log(render({ id: 7, items: [{ name: 'bolt <M8>', qty: 3 }] }));

Most used: `${value}` template literals, Array.map(...).join(''), tagged templates, String.raw, Handlebars or EJS for template files.