The process object
process.argv, env, exit codes, signals, cwd, stdout and stderr, hrtime and memoryUsage, and the process.exit() trap that truncates output.
The process object
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `process` is a global that represents the running program: its arguments (`argv`), environment (`env`), working directory (`cwd()`), standard streams (`stdout`, `stderr`, `stdin`) and lifecycle events. In ES modules you can also `import process from 'node:process'`.
- `process.argv[0]` is the path to Node, `argv[1]` is the script, and your own arguments start at index 2. For anything beyond a couple of flags use `util.parseArgs` instead of parsing by hand.
- Exit codes are how a program tells its caller whether it worked: 0 is success, anything else is failure. Prefer setting `process.exitCode` and letting the event loop drain over calling `process.exit()`, which can cut off output that has not been flushed yet.
- A signal is a message from the operating system. `SIGINT` (Ctrl+C) and `SIGTERM` (what Docker and Kubernetes send on shutdown) can be handled to clean up; `SIGKILL` cannot be caught. Exiting through a signal gives code 128 plus the signal number: 130 for SIGINT, 137 for SIGKILL.
- Write data to `stdout` and diagnostics to `stderr`, so that piping a program's output into another command does not mix the two.
A program needs to know about itself
A script that cannot see its own command line, environment or exit status is not much use outside a toy. Node gives you all of it through one global, process. It is an EventEmitter and an object full of properties describing the running program, and it is the bridge between your code and the shell that started it.
import process from 'node:process'; // optional: process is also a global
console.log(process.argv.slice(2)); // arguments you passed
console.log(process.env.HOME); // environment variables (strings or undefined)
console.log(process.cwd()); // working directory
console.log(process.platform, process.version);
Running node proc.js a --b=1 prints [ 'a', '--b=1' ]. The first two entries of process.argv are the Node binary (process.execPath) and the script path, which is why your arguments start at index 2. For more than a handful of flags, do not hand-parse them; util.parseArgs is built in and is covered in building command-line tools.
process.env is a plain object of strings. process.env.PORT is "4000", not the number 4000, and a missing variable is undefined. Loading and validating it properly is the subject of configuration and environment variables.
Standard streams: stdout versus stderr
process.stdout, process.stderr and process.stdin are streams. console.log writes to stdout and console.error writes to stderr. The split exists so that when someone runs your-tool | jq ., only the data goes into the pipe and your error messages still reach their screen. Warnings and logs belong on stderr; results belong on stdout. process.stdout.isTTY tells you whether a human is on the other end, which is how tools decide whether to print colour.
Exit codes
Every process ends with a number. The shell exposes it as $?, CI uses it to decide whether a step passed, and Kubernetes uses it to decide whether to restart. Zero means success. Anything else means failure. Node’s own codes include 1 for an uncaught exception, which you can confirm:
node -e "throw new Error('x')"; echo $? # 1
node -e "process.exitCode = 4; process.exit()"; echo $? # 4
There are two ways to set the code. process.exit(code) ends the process on the spot. process.exitCode = code records the code and lets the program finish naturally. Prefer the second.
The process.exit() trap
process.exit() does not wait for pending writes. When standard output is a pipe, writes can be asynchronous, so output can be cut off:
node -e "process.stdout.write('x'.repeat(1e6)); process.exit(0)" | wc -c # 65536 on macOS
node -e "process.stdout.write('x'.repeat(1e6)); process.exitCode = 0" | wc -c # 1000000
The exact truncation point depends on the platform and the pipe size, but the pattern is real and is a common source of mysteriously incomplete log files and CLI output. Set exitCode, let the event loop drain, and reserve process.exit() for cases where you truly must stop now.
Lifecycle events
process.on('beforeExit', (code) => { /* loop is empty; you may schedule more work */ });
process.on('exit', (code) => { /* synchronous only; the process is ending */ });
beforeExit fires when the event loop has nothing left, and scheduling a timer inside it keeps the process alive. exit fires at the very end and can only run synchronous code. Errors that nothing caught arrive as uncaughtException and unhandledRejection, which have their own lesson: handling uncaught errors and rejections.
Signals
A signal is a message from the operating system or another process. Two matter most:
SIGINTis what Ctrl+C sends.SIGTERMis the polite “please stop” thatkill <pid>, Docker and Kubernetes send during a shutdown.
process.on('SIGTERM', () => {
console.log('got SIGTERM, cleaning up');
// close the server, flush logs, close the DB pool...
process.exit(0);
});
Without a handler, Node’s default action is to die immediately. With one, you decide what happens, which is how a server finishes in-flight requests before leaving. SIGKILL (kill -9) cannot be caught or ignored, so the program gets no chance to clean up. A process that dies from a signal reports 128 plus the signal number: 130 for SIGINT and 137 for SIGKILL, which is the “exit code 137” you meet in container logs. The full shutdown sequence for a web server is in health checks and graceful shutdown and deploying Node applications.
Measuring: hrtime and memoryUsage
process.hrtime.bigint() returns a monotonic nanosecond counter for timing code; unlike Date.now() it never jumps when the system clock changes. process.memoryUsage() returns rss, heapTotal, heapUsed, external and arrayBuffers in bytes, and process.memoryUsage.rss() is a cheaper call when you only want the resident set size. process.uptime() is seconds since start. These are the raw numbers behind the profiling work in profiling and finding bottlenecks and memory leaks and heap snapshots.
What the video covers
Software Developer Diaries’ video is about shutting an application down cleanly: why exiting well matters, how a Node process handles termination signals, and how that plays out in Docker and Kubernetes, with Node examples. That covers the signals and exit-codes sections here. argv, env, the stream split, hrtime and memoryUsage come from the prose, and the short process.argv video under “go deeper” covers arguments. No transcript was available, so this reflects the title and description. The video is from September 2024 and contains nothing tied to a specific Node version.
Where this fits
With process in hand you can read what a script was given and say how it ended. The next two lessons explain what the event loop does between those two points: the event loop phases and blocking vs non-blocking I/O.
Check yourself
A script prints 1,000,000 bytes to a pipe and then calls `process.exit(0)`. Why might the reader get fewer bytes, and what is the fix?
Writes to a pipe can be asynchronous. `process.exit()` ends the process immediately, so whatever was still waiting to be flushed is lost. In a test on macOS only 65,536 of 1,000,000 bytes arrived. Set `process.exitCode = 0` and let the event loop finish, and all bytes arrive.
What exit code does a shell report when a Node process is killed with `kill -9`, and why?
137. Processes that die from a signal report 128 plus the signal number, and SIGKILL is signal 9. SIGINT (signal 2) gives 130. A process cannot run any cleanup on SIGKILL, so handlers for it are not possible.
Your script prints progress lines and a JSON result with `console.log`, and piping it into `jq` fails to parse. What is the fix?
Progress and diagnostics should go to `stderr` (`console.error` or `process.stderr.write`), and only the JSON result to `stdout`. A pipe carries `stdout` only, so `jq` then sees clean JSON while the human still sees the progress on the terminal.
What is the difference between the `beforeExit` and `exit` events?
`beforeExit` fires when the event loop has run out of work, and a handler can schedule more work to keep the process alive. `exit` fires when the process is really about to end, whether because of `process.exit()` or because the loop emptied, and handlers there can only run synchronous code.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.