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: concurrency & network

Doing several things at once and talking to other machines: threads and tasks, locks and atomics, CPU parallelism, event loops, cancellation, request context, sockets, TLS and HTTP.

Concurrency: Promise, sync + goroutines, std::thread/std::sync, <thread>

TypeScript

JavaScript runs your code on one thread with an event loop, so concurrency means overlapping I/O rather than running CPU work in parallel. Promise is the built-in type for a value that arrives later, and async/await is its syntax. Promise.all, allSettled, race and any combine promises, and AbortController cancels operations such as fetch. CPU-heavy work moves to node:worker_threads.

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 { setTimeout as sleep } from 'node:timers/promises';

async function fetchPrice(id: number): Promise<number> {
  await sleep(10 * id); // stands in for I/O
  return id * 100;
}

// One thread, many operations in flight: start them all, then wait for all.
const prices = await Promise.all([1, 2, 3].map(fetchPrice));
console.log(prices);

const first = await Promise.race([fetchPrice(3), sleep(5, 'timeout')]);
console.log(first);

Most used: async/await, Promise.all, Promise.allSettled, Promise.race, AbortController, setTimeout from node:timers/promises, worker_threads.

Locks, atomics & one-time init: Atomics, sync.Once, OnceLock, std::call_once

TypeScript

JavaScript code on one thread never runs two statements at once, so ordinary Node programs need no locks. Memory is shared only when you hand a SharedArrayBuffer to worker_threads; then the Atomics functions read and modify it without lost updates, and Atomics.wait and Atomics.notify let one thread sleep until another changes a cell. Atomics.wait blocks the calling thread (allowed on the Node main thread, but it freezes the event loop), and Atomics.waitAsync returns a promise instead. A lazily created module-level promise covers one-time initialisation.

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 { Worker, isMainThread, workerData } from 'node:worker_threads';

if (isMainThread) {
  const shared = new SharedArrayBuffer(8); // two Int32 cells: [count, start gate]
  const cells = new Int32Array(shared);
  const workers = [1, 2, 3, 4].map(
    () => new Worker(new URL(import.meta.url), { workerData: shared }) // same bytes, not a copy
  );

  Atomics.store(cells, 1, 1); // open the gate...
  Atomics.notify(cells, 1); // ...and wake every worker sleeping on it
  await Promise.all(workers.map((worker) => new Promise((done) => worker.once('exit', done))));
  console.log('count:', Atomics.load(cells, 0));
} else {
  const cells = new Int32Array(workerData as SharedArrayBuffer);
  Atomics.wait(cells, 1, 0); // sleep while the gate is still 0 (returns at once if already open)
  for (let i = 0; i < 1000; i++) {
    Atomics.add(cells, 0, 1); // cells[0]++ here could lose updates between threads
  }
}

Most used: new SharedArrayBuffer, Int32Array views, Atomics.add, Atomics.load, Atomics.store, Atomics.compareExchange, Atomics.wait, Atomics.notify, Atomics.waitAsync.

postMessage copies ordinary values; only a SharedArrayBuffer (or a transferred buffer) is shared, so most worker code needs no Atomics at all.

Atomics only work on integer typed arrays (Int32Array or BigInt64Array for wait and notify) over shared memory.

CPU parallelism & worker pools: worker_threads, errgroup, rayon, std::jthread

TypeScript

Promises overlap waiting, not computing: CPU-heavy JavaScript blocks the event loop until it finishes. node:worker_threads runs a module on another thread with its own event loop and heap; workerData passes its input, and postMessage sends results back as structured-clone copies. os.availableParallelism() says how many threads are worth starting. Starting a worker costs milliseconds, so long-lived pools (piscina is the common library) beat one worker per task.

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 { availableParallelism } from 'node:os';
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';

function countPrimes(from: number, to: number): number {
  let count = 0;
  for (let n = Math.max(from, 2); n < to; n++) {
    let prime = true;
    for (let d = 2; d * d <= n && prime; d++) prime = n % d !== 0;
    if (prime) count++;
  }
  return count;
}

if (isMainThread) {
  const limit = 200_000;
  const threads = Math.min(4, availableParallelism());
  const size = Math.ceil(limit / threads);
  const counts = await Promise.all(
    Array.from({ length: threads }, (_, i) => {
      const range = { from: i * size, to: Math.min(limit, (i + 1) * size) };
      const worker = new Worker(new URL(import.meta.url), { workerData: range }); // this file again
      return new Promise<number>((resolve, reject) => {
        worker.once('message', resolve);
        worker.once('error', reject);
      });
    })
  );
  console.log('primes below', limit, '=', counts.reduce((a, b) => a + b));
} else {
  const { from, to } = workerData as { from: number; to: number };
  parentPort!.postMessage(countPrimes(from, to)); // copied back to the main thread
}

Most used: new Worker(url, { workerData }), isMainThread, workerData, parentPort.postMessage, worker.on("message"), worker.on("error"), worker.terminate(), os.availableParallelism(), transfer lists for ArrayBuffers.

Each worker has its own module instances and globals: state set in the main thread is not visible in a worker.

Large ArrayBuffers can be moved instead of copied by listing them in postMessage’s transfer list.

Event loops & async runtimes: EventEmitter, the Go scheduler, tokio, Asio

TypeScript

Node runs everything on one event loop: callbacks, timers, I/O completions and promise continuations are queued and run one at a time, so a long synchronous computation blocks everything else. node:events provides EventEmitter, the publish-subscribe base class behind streams, servers and sockets (on, once, emit, off), and events.once turns an event into a promise. EventTarget is the web-standard equivalent.

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 { EventEmitter, once } from 'node:events';

class OrderQueue extends EventEmitter<{ order: [id: number]; drained: [] }> {
  private pending: number[] = [];

  add(id: number) {
    this.pending.push(id);
    this.emit('order', id); // listeners run synchronously, in order
  }

  drain() {
    this.pending = [];
    queueMicrotask(() => this.emit('drained')); // after the current code finishes
  }
}

const queue = new OrderQueue();
queue.on('order', (id) => console.log('received', id));
queue.add(7);
queue.drain();
await once(queue, 'drained'); // turn one event into a promise
console.log('drained');

Most used: EventEmitter, on, once, emit, off, events.once, events.on as an async iterator, queueMicrotask, setImmediate, EventTarget.

Cancellation & deadlines: AbortController, context, CancellationToken, std::stop_token

TypeScript

AbortController and AbortSignal are the standard cancellation mechanism. Pass the signal to anything that accepts one (fetch, timers/promises, stream.pipeline, child_process and many libraries); calling abort() makes those operations reject with an AbortError, and signal.reason says why. AbortSignal.timeout(ms) creates a deadline (its reason is a TimeoutError) and AbortSignal.any combines several signals. Your own async functions should accept a signal and check signal.aborted or listen for its abort event.

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 { setTimeout as sleep } from 'node:timers/promises';

async function fetchReport(signal: AbortSignal): Promise<string> {
  await sleep(1000, undefined, { signal }); // stands in for slow I/O; rejects on abort
  return 'report';
}

const controller = new AbortController();
setTimeout(() => controller.abort(), 50); // cancel by hand...

for (const signal of [controller.signal, AbortSignal.timeout(20)]) { // ...or by deadline
  try {
    console.log(await fetchReport(signal));
  } catch {
    console.log('stopped:', signal.reason.name); // AbortError by hand, TimeoutError by deadline
  }
}

Most used: new AbortController(), controller.abort(), { signal } options, AbortSignal.timeout, AbortSignal.any, signal.throwIfAborted(), signal.addEventListener('abort').

Request-scoped context: AsyncLocalStorage, context.WithValue, task_local!, thread_local

TypeScript

AsyncLocalStorage from node:async_hooks carries a value through everything that one call starts: awaits, timers, promise callbacks and event-emitter callbacks registered inside it. run(store, fn) makes store visible to getStore() for the duration of fn and its async continuations, so concurrent requests each see their own value without passing it through every function. Loggers and tracing (OpenTelemetry) use it for request ids.

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 { AsyncLocalStorage } from 'node:async_hooks';
import { setTimeout as sleep } from 'node:timers/promises';

type RequestContext = { requestId: string; user: string };
const requestContext = new AsyncLocalStorage<RequestContext>();

function log(message: string) {
  const id = requestContext.getStore()?.requestId ?? '-'; // undefined outside run()
  console.log(`[${id}] ${message}`);
}

async function loadOrders(delay: number) {
  await sleep(delay); // the store survives awaits and timers
  log(`orders for ${requestContext.getStore()?.user}`);
}

function handle(requestId: string, user: string, delay: number) {
  return requestContext.run({ requestId, user }, async () => {
    log('start');
    await loadOrders(delay);
    log('done');
  });
}

await Promise.all([handle('r1', 'ada', 20), handle('r2', 'lin', 10)]); // interleaved, never mixed
log('outside');

Most used: new AsyncLocalStorage<T>(), als.run(store, fn), als.getStore(), als.exit(fn), AsyncLocalStorage.bind, AsyncLocalStorage.snapshot.

getStore() returns undefined outside run(), so code that reads it must handle the missing case.

Keep stores small and treat them as read-only: anything mutated in a store is visible to every continuation of that request.

TCP & UDP sockets: node:net, net, std::net, Boost.Asio

TypeScript

node:net provides TCP servers and clients (and Unix domain sockets): createServer hands you each connection as a Duplex stream and createConnection opens one. node:dgram handles UDP, and node:tls adds encryption with the same shape. Sockets are event-driven (data, end, error and close events), and TCP delivers a byte stream rather than messages, so framing is up to you.

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 { createConnection, createServer } from 'node:net';

// An echo server: each connection is a duplex stream of bytes.
const server = createServer((socket) => socket.pipe(socket));

server.listen(0, '127.0.0.1', () => {
  const { port } = server.address() as { port: number }; // port 0 picked a free port
  const client = createConnection({ port, host: '127.0.0.1' }, () => client.end('ping\n'));
  client.on('data', (data) => console.log('echoed:', data.toString().trim()));
  client.on('close', () => server.close());
});

Most used: net.createServer, server.listen, net.createConnection, socket.write, socket.on('data'), socket.end, dgram.createSocket, tls.connect.

TLS & certificates: node:tls, crypto/tls + crypto/x509, rustls, OpenSSL

TypeScript

node:tls opens encrypted connections: tls.connect for clients and tls.createServer for servers, with the same stream API as node:net; https and fetch use it underneath. Verification is on by default against Node's bundled Mozilla roots. To trust a private CA, pass ca (which replaces the defaults; append to tls.rootCertificates to keep them), set NODE_EXTRA_CA_CERTS=file.pem before Node starts, or use --use-system-ca (Node 22.15+) for the operating system's store. Unlike https, tls.connect sends no SNI unless you set servername.

Complete program

Complete program; needs network access to example.com.

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

// Verification is on by default: the chain must end at a trusted root and the name must match.
const socket = connect(
  {
    host: 'example.com',
    port: 443,
    servername: 'example.com', // SNI; tls.connect does not send it unless you set it
    minVersion: 'TLSv1.2'
  },
  () => {
    const cert = socket.getPeerCertificate(); // the server's leaf certificate
    console.log(socket.authorized, socket.getProtocol());
    console.log(cert.subject.CN, cert.subjectaltname?.includes('DNS:example.com'));
    socket.end();
  }
);
socket.on('error', (error) => console.error('TLS failed:', error)); // bad chain, wrong name, expired...

Most used: tls.connect({ host, port, servername }), socket.authorized, socket.getProtocol(), socket.getPeerCertificate(), minVersion, ca, tls.createServer({ key, cert }), https.request with ca or an https.Agent, NODE_EXTRA_CA_CERTS.

Never set rejectUnauthorized: false or NODE_TLS_REJECT_UNAUTHORIZED=0 outside a throwaway test: the connection stays encrypted, but to whoever answers, so anyone on the network path can impersonate the server and read everything. Trust the right CA with ca or NODE_EXTRA_CA_CERTS instead.

Output depends on the server: example.com currently negotiates TLS 1.3.

HTTP: fetch + node:http, net/http, reqwest/axum, cpp-httplib

TypeScript

Two built-ins cover HTTP. fetch is the client (the same API as in browsers; stable since Node 21): it returns a Response with status, headers, json() and text(), and it does not reject on 4xx or 5xx, so check response.ok. node:http (and node:https) is the low-level server. Most applications put a framework such as Express, Fastify or Hono on top for routing and middleware.

Complete program

Complete program that needs network access; it keeps serving until stopped.

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

// Client: fetch is built into Node 18+ and browsers.
const response = await fetch('https://example.com/');
console.log(response.status, response.headers.get('content-type'));

// Server: node:http is the low-level built-in server.
const server = createServer((request, reply) => {
  reply.writeHead(200, { 'Content-Type': 'application/json' });
  reply.end(JSON.stringify({ path: request.url }));
});
server.listen(8080, () => console.log('listening on :8080'));

Most used: fetch, response.ok, response.json(), AbortSignal.timeout, http.createServer, server.listen.