os and process
node:os exposes host capabilities; process exposes the current Node runtime - together they drive cluster sizing, health payloads, and environment configuration.
Recipe
import { availableParallelism, hostname, totalmem, freemem } from 'node:os';
console.log({
host: hostname(),
cpus: availableParallelism(),
memFree: freemem(),
memTotal: totalmem(),
node: process.version,
pid: process.pid,
});When to reach for this:
/healthand/readydiagnostic payloads- Sizing worker_threads pools and cluster forks
- Logging platform in structured startup banner
- Detecting container memory pressure before OOMKill
Working Example
import { availableParallelism, hostname, loadavg, platform, arch } from 'node:os';
export function hostSnapshot() {
return {
hostname: hostname(),
platform: platform(),
arch: arch(),
nodeVersion: process.version,
pid: process.pid,
ppid: process.ppid,
uptimeSec: process.uptime(),
cpuParallelism: availableParallelism(),
loadavg1m: loadavg()[0],
memory: process.memoryUsage(),
env: process.env.NODE_ENV ?? 'development',
};
}
export function assertProductionEnv(): void {
if (process.env.NODE_ENV === 'production' && !process.env.DATABASE_URL) {
throw new Error('DATABASE_URL required in production');
}
}import { monitorEventLoopDelay } from 'node:perf_hooks';
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
setInterval(() => {
console.log('eventLoopP99Ns', h.percentile(99), 'rss', process.memoryUsage().rss);
h.reset();
}, 30_000).unref();What this demonstrates:
availableParallelismrespects cgroup CPU limits in containers better than legacycpus().lengthprocess.memoryUsage().rsstracks resident set - correlate with K8s OOM eventsloadavgUnix-specific - useful on Linux VMs, less on Windows- Validate critical env at boot before accepting traffic
Deep Dive
How It Works
- process.env is mutable string map - copy at boot for immutability if desired.
- memoryUsage returns rss, heapTotal, heapUsed, external - not full process footprint but trendable.
- cpuUsage microsecond user/system time for current process.
- os.networkInterfaces lists NIC addresses - filter carefully before logging (PII/internal topology).
Useful Fields
| API | Meaning |
|---|---|
process.uptime() | Seconds since Node start |
process.ppid | Parent PID (1 in Docker after init) |
freemem() | OS free RAM |
tmpdir() | Temp directory path |
TypeScript Notes
import { env } from 'node:process';
const nodeEnv = env.NODE_ENV ?? 'development';Gotchas
- Logging full process.env - secrets leak. Fix: allowlist keys in health output.
- Using cpus().length in containers - wrong vCPU count. Fix:
availableParallelism(). - Mutating process.env at runtime - subtle bugs in libraries. Fix: treat as immutable after bootstrap.
- Trusting hostname for security - spoofable context. Fix: authz not based on hostname alone.
- loadavg on Windows - returns zeros - do not rely cross-platform.
Alternatives
| Alternative | Use When | Don't Use When |
|---|---|---|
| K8s metrics-server | Fleet memory/cpu | Local dev only |
| OpenTelemetry host metrics | Unified observability | Quick one-off script |
/proc/self Linux read | Deep container debug | Portable app code |
| Cloud instance metadata | AZ/region detection | On-prem bare metal |
FAQs
availableParallelism vs cpus().length?
Parallelism respects cgroup limits in Kubernetes - preferred for pool sizing.
What is rss?
Resident Set Size - physical RAM used by process - watch for OOM trends.
process.exit vs natural exit?
exit skips async cleanup - prefer graceful shutdown then natural exit.
How to read NODE_ENV?
process.env.NODE_ENV - validate with Zod at startup.
os.homedir usage?
User home paths - rare in server containers - prefer explicit config paths.
process.title?
Set process title for ps visibility - optional ops convenience.
argv and execArgv?
argv user args; execArgv node flags like --import tsx.
container memory limits?
freemem is host view - cgroup limit needs cgroups fs or external agent for accurate headroom.
Windows platform()
Returns win32 - path and signal semantics differ from Linux.
health endpoint fields?
version, uptime, pid, optional elu - avoid full host dump publicly.
relation to cluster?
cluster Module uses availableParallelism.
process.report?
Diagnostic report on crash - see Reading Official Docs.
Related
- Processes Basics - pid and workers
- Installing & Version Management - engines
- Detecting Event-Loop Blockage - perf_hooks
- Configuration Basics - env patterns
Stack versions: This page was written for Node.js 24.18.0 (Active LTS), npm 10+, TypeScript 5.6+, Express 5, Fastify 5, and NestJS 11.