Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 133 ยท The Runtime

The process Object

Learn the Node.js process object - argv, env, cwd, exit codes, exit and beforeExit events, signals like SIGTERM, stdin and stdout streams, hrtime and memory usage.

Every running Node.js program has one object that represents itself: process. It is a global, so there is nothing to import. Through it you read the command-line arguments and environment variables, find out where you are running, decide the exit code, react to signals such as Ctrl+C, and reach the standard input and output streams. If window is the browser's view of the page, process is Node's view of the operating-system process your code lives in.

This lesson tours the parts of process you will use in nearly every real program. You will meet several of them again later: configuration in Configuration, Secrets and Environment, signals in Graceful Shutdown, and command-line parsing in Building Command-Line Tools.

Command-line arguments: process.argv

process.argv is an array of strings. Element 0 is the path of the Node executable, element 1 is the path of the script being run, and everything after that is what the user typed. So the useful arguments start at index 2, which is why you will see process.argv.slice(2) so often.

Terminal
node greet.mjs Maya --shout
TEXT
process.argv = [ '/usr/bin/node', '/home/me/greet.mjs', 'Maya', '--shout' ]

Our editor runs your code without extra arguments, but you can still see the shape and write the logic that handles them. This example parses a made-up argument list the same way it would parse the real one.

Node.js Looking at argv and parsing a made-up argument list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

process.execArgv holds flags meant for Node itself (such as --enable-source-maps), kept apart from your program's arguments. For anything beyond a couple of flags, use util.parseArgs, covered in The util Module, rather than hand-rolling a parser.

Environment variables: process.env

process.env is an object holding the environment variables of the process, such as PATH, HOME or whatever your deployment sets (PORT, NODE_ENV, DATABASE_URL). It is the standard way to configure a program without changing its code.

Two properties surprise people. Every value is a string (or undefined if the variable is missing), and assigning anything else converts it to a string, including the strings "undefined" and "null".

Node.js Reading, defaulting and the string-only rule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Changing process.env only affects your own process and the children you start afterwards; it never changes your shell. Always convert and validate at the edges: Number(...), comparing to 'true', and failing fast with a clear message when a required variable is missing. Never log the whole object; it often contains secrets.

Where am I running?

A handful of read-only properties tell you about the environment. They are useful for diagnostics and for the rare code that must behave differently per operating system.

Node.js Facts about the process

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

process.cwd() is the current working directory: the folder relative paths resolve against. It is where the user started the program, not where your script lives; use import.meta.dirname for the latter. process.chdir(dir) changes it for the whole process, which is global state and best avoided. process.platform returns values like 'linux', 'darwin' (macOS) or 'win32' (Windows, even on 64-bit), and process.arch something like 'x64' or 'arm64'.

Exiting: exit codes

When a program ends, it reports an exit code to whoever started it. By convention 0 means success and any other number means failure. Shells, CI systems and process managers all depend on it: npm test && deploy only deploys if the tests exit with 0.

There are two ways to set it:

  • process.exitCode = 2; records the code but lets the program finish naturally, so pending work can complete. This is the preferred way.
  • process.exit(2); ends the process immediately. Pending timers, unfinished writes to pipes and open handles are abandoned.

Without either, the exit code is 0 when the event loop empties, and 1 when an uncaught error crashes the program.

Node.js exitCode lets pending work finish, exit() does not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The editor's note under the output shows the final exit code, 5. The first timer ran, the last one did not. Use process.exit() only when you really must stop now (for instance, a fatal startup error after you have logged it); in a server you want a graceful shutdown that closes connections first.

process.exit() can cut off output that is still being written to a pipe, so a log line printed just before it may never appear when the output is piped to another program. Setting process.exitCode and letting the loop drain avoids that.

The exit and beforeExit events

Two events let you run code at the end of a program's life, and they differ in an important way.

  • 'beforeExit' fires when the event loop has run out of work and Node is about to exit. It does not fire for process.exit() or an uncaught error. You may schedule more asynchronous work in the handler, which keeps the process alive.
  • 'exit' fires when the process is really about to end, whatever the reason, including process.exit(). Handlers must be synchronous: anything asynchronous scheduled here never runs.
Node.js beforeExit versus exit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

beforeExit ran twice: once when the program first went idle, and again after the extra work finished (this time we did not add more). Then exit fired exactly once. Use 'exit' for last-moment synchronous cleanup, such as deleting a temporary file, and remember it cannot do any asynchronous work.

Signals

A signal is a small message the operating system (or another program) sends to a process. The two you will meet most are SIGINT, sent when the user presses Ctrl+C, and SIGTERM, sent politely by tools such as kill, Docker and Kubernetes when they want the program to stop. By default both terminate the process at once. If you register a handler, the default is replaced and you decide what happens, which is how a server finishes its in-flight requests before quitting.

You can send a signal to yourself with process.kill(process.pid, 'SIGTERM'), which is handy for testing a handler. On Linux and macOS this works as shown; on Windows only a few signals are emulated, and SIGTERM simply kills the process, so this example is specific to Unix-like systems such as our server.

Node.js Handling SIGTERM and SIGINT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The handler runs asynchronously (after the current synchronous code), the second signal is recognised and ignored, and the cleanup timer completes before the process exits. Two rules apply to real handlers: do the work quickly and idempotently, and end the process explicitly with process.exit() (or by letting handles drain), because once you handle a signal Node will no longer stop on its own. SIGKILL and SIGSTOP can never be caught.

Standard streams: stdin, stdout, stderr

Every process starts with three channels. process.stdout and process.stderr are writable streams; process.stdin is a readable stream. console.log is a convenience that writes a formatted line to stdout, and console.error to stderr. Keeping normal output on stdout and diagnostics on stderr lets users pipe one without the other (node app.js > result.txt still shows errors on screen).

Use the streams directly when you want no automatic newline, or when you read piped input. This example reads two lines supplied through the editor's Program input box.

Node.js Reading stdin, writing stdout and stderr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Because stdin is an async iterable, a for await loop collects everything until the input ends. isTTY is true when the stream is a real terminal and undefined when it is a pipe or file; programs use it to decide whether to print colours or progress bars. More on reading input interactively is in Interactive CLIs with readline, and on the stream APIs in Streams Fundamentals.

Time and resources

process also offers a few measuring tools.

  • process.hrtime.bigint() returns a monotonic, nanosecond-resolution clock as a BigInt. It never goes backwards (unlike Date.now() when the system clock is adjusted), so it is the right choice for measuring durations. Subtract two readings to get elapsed nanoseconds.
  • process.uptime() returns how many seconds the process has been running.
  • process.memoryUsage() returns an object with rss (total memory held by the process), heapTotal, heapUsed, external and arrayBuffers, all in bytes. The cheaper process.memoryUsage.rss() returns just the first.
  • process.cpuUsage() reports CPU time spent in user and system code, in microseconds.
Node.js Clocks and memory, shown without raw numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

We print comparisons rather than the numbers themselves, because they differ on every run and machine. In your own programs, log them or feed them to a monitoring tool. Memory is explored properly in V8, Memory and Garbage Collection.

Identity: parent process, user and group IDs

A few more process properties describe who the process is and where it came from.

  • process.pid is the process ID and process.ppid the ID of the parent process, the one that started yours (a shell, a supervisor, a test runner).
  • process.argv0 keeps the original argv[0] exactly as it was typed, for example node rather than the full path that process.argv[0] and process.execPath hold.
  • process.debugPort is the port the inspector uses when you start with --inspect (9229 by default); you can change it at run time.
  • On POSIX systems (Linux, macOS) process.getuid(), getgid(), geteuid(), getegid() and getgroups() return the numeric user and group IDs. "Effective" IDs are the ones the system checks for permissions; "real" IDs say who started the process. process.setuid(), setgid(), seteuid(), setegid() and setgroups() change them and need privileges. A common pattern is a server that starts as root to bind port 80 and then drops privileges with process.setgid() followed by process.setuid() (group first, because after the user change you may no longer be allowed to change the group). On Windows these functions do not exist, so check before calling them.
Node.js Who am I?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last safety net is a capture callback. process.setUncaughtExceptionCaptureCallback(fn) routes every uncaught exception to fn instead of the usual 'uncaughtException' event, and passing null removes it. process.hasUncaughtExceptionCaptureCallback() tells you whether one is installed. Only one callback can exist at a time, which is why this is meant for tools and frameworks (the domain module used it), not application code.

Node.js Capturing an uncaught exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Warnings and the last line of defence

process.emitWarning(message, type) prints a warning to stderr and emits a 'warning' event, which is how Node itself announces deprecations, experimental features and timer problems. You can listen for the event, for example to count warnings in a test run.

The process object also exposes two global safety nets, 'uncaughtException' and 'unhandledRejection', which fire when an error escapes everything. They are powerful and easy to misuse, so they get their own treatment in Errors and Error Handling.

Node.js Listening to warnings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The line after the emit prints first because warning events are delivered on a later tick of the loop. Node's own stderr copy of each warning also appears, but only your console.log text goes to the normal output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where do the arguments typed by the user start in process.argv?

    argv[0] is the node executable and argv[1] is the script, so process.argv.slice(2) gives the user's arguments.
  2. 2. After process.env.COUNT = 10, what does typeof process.env.COUNT return?

    Environment variable values are always strings; assigned values are converted.
  3. 3. What is the difference between setting process.exitCode and calling process.exit(code)?

    process.exitCode is applied when the program ends naturally, so timers and writes can complete. process.exit() abandons them.
  4. 4. What can you NOT do inside a handler for the process 'exit' event?

    By the time 'exit' fires the event loop has stopped, so only synchronous code can run.
  5. 5. Why register a handler for SIGTERM in a server?

    Without a handler SIGTERM terminates the process immediately. A handler lets you shut down gracefully. SIGKILL can never be caught.

Summary

  • process is a global describing the running program: arguments, environment, working directory, platform and version.
  • User arguments start at process.argv[2]; flags for Node itself are in process.execArgv.
  • process.env values are always strings; validate and convert them, and never log the whole object.
  • Prefer process.exitCode over process.exit() so pending work finishes; 0 means success, non-zero means failure.
  • 'beforeExit' can schedule more async work; 'exit' handlers must be synchronous.
  • Handle SIGINT and SIGTERM to shut down gracefully; SIGKILL cannot be caught.
  • stdout, stderr and stdin are streams; keep results on stdout and diagnostics on stderr.
  • Use process.hrtime.bigint() for durations and process.memoryUsage() for memory, but never rely on their exact values in tests.

Next: Events and EventEmitter