The process and the command line

Topic 1 of 5 in The Node runtime7 min readIntermediateFree course

Overview

Every running Node program is an operating-system process, and Node gives you a global process object to talk to it. Through process your program receives input (arguments, environment variables, piped data), produces output (normal output and error messages), and reports how things went (the exit code).

These are the same conventions every command-line tool follows — git, ls, grep, npm. Learning them lets you build your own tools and, just as importantly, understand how servers are started and stopped in production.

A Node process receives command-line arguments, environment variables and stdin, and exposes process.argv, process.env, process.cwd() and process.pid. It writes normal output to stdout, errors and logs to stderr, and finishes with an exit code where 0 means success. Signals such as SIGINT and SIGTERM arrive as process events.

Useful process properties

JavaScript
process.argv;          // command-line arguments
process.env;           // environment variables (next topic)
process.cwd();         // the folder the command was run from
process.pid;           // this process's ID
process.platform;      // 'linux', 'darwin', 'win32'
process.version;       // 'v26.4.0'
process.memoryUsage(); // { rss, heapUsed, heapTotal, … } in bytes
process.uptime();      // seconds since the process started

process.cwd() is not the script’s folder. It’s wherever the user was when they ran the command. To find files next to your code, use import.meta.dirname instead (see Paths and URLs).

Parsing arguments

process.argv gives you raw strings. For flags and options, use parseArgs from node:util:

JavaScript
// resize.js
import { parseArgs } from 'node:util';

const { values, positionals } = parseArgs({
  allowPositionals: true,
  options: {
    width: { type: 'string', short: 'w', default: '800' },
    quality: { type: 'string', short: 'q', default: '80' },
    overwrite: { type: 'boolean', default: false },
    help: { type: 'boolean', short: 'h' },
  },
});

if (values.help || positionals.length === 0) {
  console.log('Usage: node resize.js [--width 800] [--overwrite] <files…>');
  process.exit(0);
}

console.log(values, positionals);
Terminal
node resize.js -w 1200 --overwrite a.jpg b.jpg
# { width: '1200', quality: '80', overwrite: true } [ 'a.jpg', 'b.jpg' ]

Option values arrive as strings — convert numbers with Number(). Unknown options throw an error, which protects users from typos like --widht.

Standard streams

Every process has three standard streams:

Stream Node object Used for
stdin process.stdin input typed or piped in
stdout process.stdout the program’s normal output
stderr process.stderr errors, warnings, progress messages

console.log writes to stdout; console.error and console.warn write to stderr. Keeping them separate lets people pipe your real output elsewhere while still seeing errors:

Terminal
node export.js > users.csv          # data goes to the file, errors still show on screen
node export.js 2> errors.log        # errors go to a file
node export.js | grep "@gmail.com"  # data flows into another program

Reading piped input

JavaScript
import { text } from 'node:stream/consumers';

const input = await text(process.stdin); // read everything piped in
console.log(input.toUpperCase());
Terminal
echo "hello" | node shout.js   # HELLO

process.stdin.isTTY is true when a person is typing at a terminal and undefined when input is piped — useful for showing help instead of waiting forever.

Exit codes

When a process ends it reports a number: 0 for success, anything else for failure. Shells, CI pipelines, Docker and process managers all rely on it — a failing npm test stops a deployment because its exit code isn’t 0.

JavaScript
if (!fileExists) {
  console.error(`File not found: ${file}`);
  process.exitCode = 1; // finish normally, then exit with 1
  return;
}

There are two ways to set the code:

  • process.exitCode = 1 — Node exits with that code once everything has finished. This is the safe default: pending writes to files and stdout complete first.
  • process.exit(1) — stops immediately, even if output is still being written or requests are in flight. Use it only when you truly must stop now.

Node itself exits with code 1 when an exception is never caught.

Signals

The operating system tells processes to stop by sending signals:

  • SIGINT — the user pressed Ctrl + C.
  • SIGTERM — a polite “please shut down”, sent by Docker, Kubernetes, systemd and hosting platforms when deploying or scaling.
  • SIGKILL — immediate termination; it can’t be caught.

You can listen for the first two and clean up — finish writing a file, close database connections — before exiting:

JavaScript
let stopping = false;

async function shutdown(signal) {
  if (stopping) return;
  stopping = true;
  console.error(`${signal} received, cleaning up…`);
  await saveProgress();
  process.exit(0);
}

process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);

You’ll build on this in Graceful shutdown and health checks, where it’s essential for zero-downtime deployments.

Making a script executable

On macOS and Linux, add a shebang line at the top and mark the file executable:

JavaScript
#!/usr/bin/env node
console.log('I run like any other command');
Terminal
chmod +x tool.js
./tool.js

To install your tool as a command (mytool instead of node tool.js), add a bin field to package.json: "bin": { "mytool": "./tool.js" }, then run npm link while developing.

Good CLI manners: print help with --help, send errors to stderr, return a non-zero exit code on failure, and never wait for input when nothing is piped in.

Exercise

A word-count CLI

Write wc.js that reads text piped into stdin and prints the number of lines and words. Support a --json flag that prints { lines, words } instead. Exit with code 1 and a message on stderr if no input arrives.

JavaScript
// Usage: cat notes.txt | node wc.js --json
import { parseArgs } from 'node:util';

Summary

  • process describes the running program: arguments, environment, working directory, memory and more.
  • Parse flags with util.parseArgs instead of slicing process.argv by hand.
  • Write results to stdout and errors to stderr, so output can be piped and redirected.
  • Exit code 0 means success; anything else means failure — set process.exitCode.
  • Handle SIGINT and SIGTERM to clean up before exiting.