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: system & OS

The operating system around a program: arguments and environment, files and paths, streams, child processes, signals, platform information, command-line options and logging.

TypeScript docs Node.js API index ↗

Process, arguments & environment: process, os, std::env, <cstdlib>

TypeScript

process is Node's handle on the running program: argv (command-line arguments after the node binary and script path), env (environment variables, always strings), cwd(), pid, exitCode and exit(), the stdin/stdout/stderr streams, and signal events such as SIGINT. It is a global, but importing node:process makes the dependency explicit.

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 process from 'node:process';

const args = process.argv.slice(2); // skip the node binary and script path
const port = process.env.PORT ?? '3000'; // string | undefined
console.log(`args=${args.join(',')} port=${port}`);
console.log(`cwd=${process.cwd()} pid=${process.pid}`);

if (args.includes('--fail')) {
  console.error('failing on request');
  process.exitCode = 1; // exit status once pending work finishes
}

Most used: process.argv, process.env, process.exitCode, process.exit, process.cwd, process.on('SIGINT'). util.parseArgs (node:util) parses named options.

Files & paths: node:fs, os + path/filepath, std::fs, <filesystem>

TypeScript

node:fs is Node's file-system module and node:fs/promises is its async/await form: readFile, writeFile, mkdir, readdir, stat, rm and rename. node:path builds and takes apart paths (join, resolve, basename, extname, dirname) with the right separator for the platform. Neither exists in browsers.

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 { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
import path from 'node:path';

const dir = path.join('data', 'reports'); // platform separator
await mkdir(dir, { recursive: true });

const file = path.join(dir, 'today.txt');
await writeFile(file, 'total: 3\n', 'utf8');
const text = await readFile(file, 'utf8');

console.log(path.basename(file), path.extname(file)); // today.txt .txt
console.log(text.trim(), await readdir(dir));

Most used: readFile/writeFile with 'utf8', mkdir with { recursive: true }, readdir, rm, path.join, path.resolve. The fs functions without /promises are callback or *Sync versions of the same calls.

Embedding, temp files, globs & watching: fs.glob, embed + os.MkdirTemp, tempfile, #embed

TypeScript

import.meta.dirname and import.meta.filename (Node 20.11+, stable from 22.16) give an ES module its own location, replacing CommonJS __dirname and __filename; use them to find files shipped next to the code. fs.mkdtemp with os.tmpdir() makes a uniquely named temporary directory, which you remove yourself. fs.glob (node:fs/promises, Node 22+, stable from 22.17; globSync in node:fs) matches patterns such as **/*.csv. fs.watch reports changes through the operating system (recursive works on macOS and Windows, and on Linux from Node 19.1) but can fire twice or report only "rename"; chokidar smooths this over. Node has no compile-time embedding: JSON files can be imported with with { type: 'json' } (read when the module loads), and bundlers or single executable applications (node:sea) carry other assets.

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 { glob, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';

// The module's own location (ES modules only), instead of __dirname and __filename.
console.log(path.basename(import.meta.filename), path.dirname(import.meta.filename) === import.meta.dirname);

const dir = await mkdtemp(path.join(tmpdir(), 'reports-')); // e.g. /tmp/reports-Xb3k9q
try {
  await mkdir(path.join(dir, '2026'));
  for (const name of ['a.csv', 'b.csv', 'notes.txt', '2026/c.csv']) {
    await writeFile(path.join(dir, name), 'x');
  }

  const found: string[] = [];
  for await (const file of glob('**/*.csv', { cwd: dir })) found.push(file); // relative to cwd
  console.log(found.sort());

  // Watching: const watcher = watch(dir, { recursive: true }, (event, name) => ...); watcher.close();
} finally {
  await rm(dir, { recursive: true, force: true }); // temp dirs are not cleaned up for you
}

Most used: import.meta.dirname, path.join(import.meta.dirname, ...), new URL('./file', import.meta.url), mkdtemp(path.join(tmpdir(), 'prefix-')), glob from node:fs/promises, fs.watch(dir, { recursive: true }), fs/promises watch with an AbortSignal.

import.meta.dirname exists only in ES modules loaded from files; in CommonJS use __dirname, and it is undefined for modules loaded over other schemes.

Relative paths are resolved against process.cwd(), the directory the program was started from, not the module: node scripts/main.ts and cd scripts && node main.ts read different files unless you anchor paths with import.meta.dirname.

fs.glob results come in no guaranteed order; sort them when the order matters.

Streams & buffered input: node:readline, io + bufio, std::io, <iostream>

TypeScript

Node models I/O as streams: process.stdin is a readable stream and process.stdout a writable one. node:readline turns a stream into lines (node:readline/promises adds question() for prompts), and node:stream has pipeline() for connecting streams with backpressure. For a whole file, readFile is simpler.

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 { createInterface } from 'node:readline';
import { stdin } from 'node:process';

// Read standard input line by line, e.g. `cat numbers.txt | node main.js`.
const lines = createInterface({ input: stdin, crlfDelay: Infinity });

let total = 0;
for await (const line of lines) {
  const value = Number(line.trim());
  if (Number.isFinite(value)) total += value;
}
console.log(`total: ${total}`);

Most used: readline.createInterface with for await...of, readline/promises question(), stream.pipeline, process.stdin and process.stdout.

Readable streams are async iterables: for await (const chunk of stream) reads them with backpressure, and pipeline from node:stream/promises connects a source, transforms and a destination and destroys all of them if one fails, which .pipe() does not do.

Node also has the web-standard ReadableStream, WritableStream and TransformStream (used by fetch bodies); Readable.fromWeb and Readable.toWeb convert between the two families.

Running other programs: child_process, os/exec, std::process::Command, popen

TypeScript

node:child_process starts other programs. execFile runs a program with an argument array and collects its output (wrap it with promisify to await it), spawn streams stdin, stdout and stderr for long-running programs or large output, and exec runs a command through a shell, which is convenient but unsafe with untrusted input. Options set the working directory, environment and a timeout.

Complete program

Complete program for macOS or Linux.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { execFile, spawn } from 'node:child_process';
import { promisify } from 'node:util';

const run = promisify(execFile);

// execFile passes arguments directly: no shell, so no quoting or injection problems.
const { stdout } = await run(process.execPath, ['--version'], { timeout: 5000 });
console.log('node', stdout.trim());

// spawn streams output and reports the exit code.
const child = spawn('ls', ['-1', '/'], { stdio: ['ignore', 'pipe', 'inherit'] });
let lines = 0;
child.stdout.on('data', (chunk: Buffer) => (lines += chunk.toString().split('\n').length - 1));
child.on('close', (code) => console.log(`ls exited with ${code}: ${lines > 0} output`));

Most used: execFile with promisify, spawn with stdio options, child.on('close'), exec (shell), fork for Node child processes, an AbortSignal for cancellation.

Signals & graceful shutdown: process signals, os/signal, tokio::signal, <csignal>

TypeScript

process emits an event for each operating-system signal: SIGINT for Ctrl-C, and SIGTERM from service managers and container runtimes. Registering a handler replaces the default immediate exit, so the handler must close servers and connections and then exit, ideally with a deadline. AbortSignal-aware code can share one AbortController that the handler aborts.

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

const server = createServer((_request, reply) => reply.end('ok\n'));
server.listen(0, () => console.log('listening; press Ctrl-C to stop'));

function shutdown(signal: NodeJS.Signals) {
  console.log(`${signal} received, closing`);
  server.close(() => process.exit(0)); // stop accepting, finish open requests
  setTimeout(() => process.exit(1), 5000).unref(); // give up after 5 s
}

process.once('SIGINT', shutdown); // Ctrl-C
process.once('SIGTERM', shutdown); // sent by service managers and containers
setTimeout(() => process.kill(process.pid, 'SIGTERM'), 100); // demo: signal ourselves

Most used: process.on('SIGINT' | 'SIGTERM'), process.once, server.close, process.exitCode, process.kill, an AbortController for shared cancellation.

Platform info & reflection: node:os, runtime + reflect, cfg/std::mem, <type_traits>

TypeScript

node:os reports on the machine: platform, arch, CPU count (availableParallelism), memory, hostname, home and temp directories, and the line ending. node:util holds general helpers: inspect (print nested objects in full), promisify (turn callback APIs into promises), parseArgs, format, types (runtime type checks) and deprecate. process.version, process.memoryUsage and process.uptime describe the running Node itself.

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 os from 'node:os';
import util from 'node:util';

console.log(os.platform(), os.arch(), os.availableParallelism() > 0, os.EOL === '\n');
console.log(os.tmpdir().length > 0, process.version.startsWith('v'));
console.log(Math.round(process.memoryUsage().heapUsed / 1e6) > 0, 'MB of heap in use');

const order = { id: 7, items: [{ name: 'bolt', tags: new Set(['m8']) }] };
console.log(util.inspect(order, { depth: null })); // the full nested structure
console.log(util.types.isPromise(Promise.resolve()), typeof order);

Most used: os.platform, os.availableParallelism, os.tmpdir, os.homedir, util.inspect, util.promisify, util.parseArgs, process.memoryUsage.

Command-line options: util.parseArgs, flag, clap, CLI11

TypeScript

node:util's parseArgs (Node 18.3+) parses named options, short aliases, booleans, defaults and positional arguments, and throws on unknown options unless strict is false. It does not generate help text; commander and yargs are the common packages when a tool needs subcommands, generated --help and validation.

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 { parseArgs } from 'node:util';

const { values, positionals } = parseArgs({
  args: ['--port', '8080', '-v', 'orders.csv'], // defaults to process.argv.slice(2)
  options: {
    port: { type: 'string', short: 'p', default: '3000' },
    verbose: { type: 'boolean', short: 'v' },
  },
  allowPositionals: true,
});

const port = Number(values.port);
console.log(port, values.verbose ?? false, positionals); // 8080 true [ 'orders.csv' ]

Most used: parseArgs({ options, allowPositionals }), values, positionals, short aliases, default, strict, commander's program.option for larger tools.

Logging: console, log/slog, tracing, std::clog

TypeScript

Node has no logging library beyond console: info and log go to standard output, warn and error to standard error, and there are no levels to filter or structured fields. That is fine for scripts. Services usually write one JSON object per line, either by hand like this or with a library such as pino or winston, so log tools can search the fields.

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+
function log(level: string, msg: string, fields: Record<string, unknown> = {}) {
  const entry = { time: new Date().toISOString(), level, msg, ...fields };
  console.log(JSON.stringify(entry)); // one JSON object per line
}

console.info('server starting'); // standard output
console.warn('cache disabled'); // standard error
console.error(new Error('connect failed')); // standard error, with stack trace

log('info', 'order created', { orderId: 7 });

Most used: console.info, console.warn, console.error, JSON.stringify for structured lines, pino in services.