Processes Basics
7 examples to get you started with Processes & Workers - 5 basic and 2 intermediate.
Prerequisites
- Node.js 24.18.0 on a multi-core host for cluster examples.
- Read How Node.js Works for single-thread JS model.
Basic Examples
1. process.pid and argv
Identify the running process and CLI arguments.
console.log('pid', process.pid);
console.log('argv', process.argv.slice(2));process.pidunique per OS process - log in structured logs.argvincludes user args afternodeand script path.- Container orchestrators identify pods by pid + hostname combo.
Related: os and process - host metadata
2. process.exit Codes
Signal success or failure to shells and CI.
function main(): void {
const ok = true;
process.exit(ok ? 0 : 1);
}- Exit code 0 is success; non-zero fails CI and systemd units.
- Prefer natural exit after async work completes -
process.exitskips I/O flush. - Uncaught exceptions exit with non-zero automatically.
3. When to Stay In-Process
I/O-bound APIs should not spawn processes per request.
import { createServer } from 'node:http';
createServer(async (req, res) => {
const data = await fetch('https://example.com').then((r) => r.text());
res.end(data.slice(0, 100));
}).listen(3000);awaityields during network I/O - no extra process needed.- Spawning per request adds latency and FD pressure.
- Scale replicas horizontally before defaulting to workers.
Related: Event Loop Best Practices - keep main thread responsive
4. worker_threads Sketch
CPU work off the main JavaScript thread.
import { Worker } from 'node:worker_threads';
const worker = new Worker(`
const { parentPort, workerData } = require('worker_threads');
parentPort.postMessage(workerData.x * 2);
`, { eval: true, workerData: { x: 21 } });
worker.on('message', (msg) => console.log(msg)); // 42- Workers share the same machine, separate V8 isolates.
workerDataclones serializable data at start.- Prefer separate
.tsworker file overeval: truein production.
Related: worker_threads - pools and SharedArrayBuffer
5. child_process spawn Sketch
Run external CLI tools as child processes.
import { spawn } from 'node:child_process';
const child = spawn('node', ['--version'], { stdio: 'inherit' });
child.on('exit', (code) => console.log('exit', code));spawnstreams stdio - good for log tailing and ffmpeg.- Avoid
shell: truewith user input - injection risk. - See child_process for
execvsspawn.
Intermediate Examples
6. cluster for HTTP Fan-Out
Fork workers to use multiple CPU cores for accept loop.
import cluster from 'node:cluster';
import { availableParallelism } from 'node:os';
import { createServer } from 'node:http';
if (cluster.isPrimary) {
const cpus = availableParallelism();
for (let i = 0; i < cpus; i++) cluster.fork();
} else {
createServer((_req, res) => res.end(`worker ${process.pid}`)).listen(3000);
}- Primary manages worker lifecycle - restart on
exitin production. - Each worker has isolated memory - no shared in-process cache.
- Kubernetes often scales pods instead of cluster module.
Related: cluster Module - production patterns
7. Graceful Shutdown Hook
Stop accepting work before exit on SIGTERM.
process.on('SIGTERM', () => {
console.log('draining...');
setTimeout(() => process.exit(0), 2000);
});- Coordinate with HTTP
server.close()and DB pool end. - See Process Signals & Shutdown for full pattern.
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.