The process Object

Info About — and Control Over — the Running Node Process

The process Object

process is the global handle to your running Node process. Args, env, exit codes, signals.

3 min read Level 1/5 #nodejs#process#signals
What you'll learn
  • Read pid, argv, env
  • Exit cleanly
  • Handle signals

process is the global Node provides for talking to the running process — its arguments, env, exit codes, and signals.

Useful Properties

process.pid;        // 12345 — process ID
process.platform;   // 'darwin' | 'linux' | 'win32'
process.arch;       // 'x64' | 'arm64'
process.version;    // 'v22.x.x'
process.argv;       // command-line args
process.env;        // environment variables
process.cwd();      // current working directory

stdout / stderr / stdin

console.log is just process.stdout.write with a newline:

process.stdout.write("no newline");
process.stderr.write("an error\n");

Read stdin (e.g. piping into your script):

let input = "";
for await (const chunk of process.stdin) {
  input += chunk;
}
console.log(`got ${input.length} chars`);
$ echo "hello" | node read-stdin.mjs
got 6 chars

Exit Codes

process.exit(0);   // success
process.exit(1);   // generic error
process.exit(2);   // your-domain error

Calling exit immediately terminates — pending IO is abandoned. Prefer letting the process exit naturally when work finishes.

Signals

Catch shutdown signals to clean up:

async function shutdown(signal) {
  console.log(`got ${signal} — closing`);
  await server.close();
  process.exit(0);
}

process.on("SIGINT",  () => shutdown("SIGINT"));   // Ctrl+C
process.on("SIGTERM", () => shutdown("SIGTERM"));  // kill / Docker stop

For HTTP servers in containers, handling SIGTERM is how you implement graceful shutdown.

Uncaught Errors

process.on("uncaughtException", (err) => {
  console.error("FATAL", err);
  process.exit(1);
});

process.on("unhandledRejection", (reason) => {
  console.error("UNHANDLED", reason);
  process.exit(1);
});

Don’t try to “recover” — log, alert, exit. Let the supervisor restart you.

The os Module →