Processes Basics
7 examples to get you started with Processes & Workers - 5 basic and 2 intermediate.
Search across all documentation pages
7 examples to get you started with Processes & Workers - 5 basic and 2 intermediate.
Identify the running process and CLI arguments.
console.log('pid', process.pid);
console.log('argv', process.argv.slice(2));process.pid unique per OS process - log in structured logs.argv includes user args after node and script path.Related: os and process - host metadata
Signal success or failure to shells and CI.
function main(): void {
const ok = true;
process.exit(ok ? 0 : 1);
}process.exit skips I/O flush.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);await yields during network I/O - no extra process needed.Related: Event Loop Best Practices - keep main thread responsive
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)); // 42workerData clones serializable data at start..ts worker file over eval: true in production.Related: worker_threads - pools and SharedArrayBuffer
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));spawn streams stdio - good for log tailing and ffmpeg.shell: true with user input - injection risk.exec vs spawn.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);
}exit in production.Related: cluster Module - production patterns
Stop accepting work before exit on SIGTERM.
process.on('SIGTERM', () => {
console.log('draining...');
setTimeout(() => process.exit(0), 2000);
});server.close() and DB pool end.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.
Reviewed by Chris St. John·Last updated Jul 19, 2026