The process object, environment variables, working directories, and exits
🎯 Introduction
By the end of this article, you will be able to read runtime configuration, determine the starting point for file paths, and report script exit status correctly.
🧱 process: a global object for the current Node.js run
process is a global object provided automatically by Node.js. Use it to read startup arguments, environment configuration, and the working directory, or to set the success or failure status returned when the program ends. It is not a function. You do not need to create, install, or import it.
For example, a file-processing script needs to know which file to process, which directory to search from, and how to report failure to the terminal. process provides these capabilities:
| Task | Member | Information or effect |
|---|---|---|
| Read startup arguments such as a filename | process.argv | Returns the startup argument array |
| Read configuration supplied by the environment | process.env | Provides environment variables such as a service port |
| Determine where relative file paths start | process.cwd() | Returns the current working directory |
| Tell the calling tool that the task failed | process.exitCode | Sets the exit code returned when the program ends |
What does “the current run” mean? main.mjs is a code file on disk. Running node main.mjs starts a Node.js process in the operating system. The process object refers to that running process, not the file on disk.
Modules loaded by the same Node.js process share one process object. Starting scripts in two terminals creates independent runs, each with its own process. It describes the current run, not every program on the computer.
Command-line arguments were demonstrated in Running programs. Next, practice environment configuration, working directories, and exit status. Replace process-demo.mjs with each set of examples and run node process-demo.mjs, except when the .env example specifies a different command.
⚙️ env: read environment configuration
Environment variables are configuration values supplied by the environment that starts a program. They suit settings such as ports that vary between environments. First create .env in the same directory:
PORT=3000
Read the port with process.env.PORT:
console.log(process.env.PORT)
Run node --env-file=.env process-demo.mjs to print 3000. The value is a string, not a number. --env-file is a built-in file-loading option in Node.js 24.19.0 and requires no package.
Without loading the file, if the system does not supply PORT either, the result is undefined. A .env file does not take effect merely by existing. An existing system environment variable with the same name generally takes precedence.
Convert and validate configuration
Reading a value successfully does not make it valid. Replace the script with:
const port = Number(process.env.PORT ?? '3000')
const valid = Number.isInteger(port) && port >= 1 && port <= 65535
console.log(valid ? port : 'Invalid port configuration')
With PORT=3000, it prints the number 3000; with PORT=abc, it prints Invalid port configuration. The range 1 through 65535 here requires an explicit service port.
Do not print all of process.env, which may contain credentials. Do not commit .env files containing sensitive data to public repositories.
📍 cwd: get the directory where the command runs
process.cwd() returns the current working directory. These examples do not change it inside the program, so it returns the directory where you launch the command.
Save this as /work/demo/process-demo.mjs:
console.log(process.cwd())
Start the same file from two locations:
Start from /work
cd /work
node demo/process-demo.mjs
This prints /work. Although the script is inside demo, the terminal is in /work when you launch it, so that is the working directory.
Start from /work/demo
cd /work/demo
node process-demo.mjs
This prints /work/demo. The terminal is now in the script's directory, so that is also the working directory.
| Terminal location at startup | Command | process.cwd() result |
|---|---|---|
/work | node demo/process-demo.mjs | /work |
/work/demo | node process-demo.mjs | /work/demo |
/work/demo is an example path; replace it with your own directory. The script remains the same file. Only the directory where you launch the command changes.
This affects file operations: reading ./config.json looks for /work/config.json in the first case and /work/demo/config.json in the second. For configuration always stored beside the script, use the module-relative approach from the path article.
🚪 exitCode: stop subsequent shell commands when a check fails
process.exitCode tells the terminal or tool that started a script whether its task succeeded or failed. For example, check port configuration before starting a service, and do not proceed if it is invalid.
console.error only displays an error to a person. The terminal does not infer success from the message; it reads the program's exit code. 0 means success; a nonzero value means failure. A script that ends normally without setting a failure code usually returns 0.
Set exitCode in the failure branch
Keep the earlier .env and create check-port.mjs:
const port = Number(process.env.PORT)
const valid = Number.isInteger(port) && port >= 1 && port <= 65535
if (!valid) {
console.error('Invalid port configuration; check PORT')
process.exitCode = 1
} else {
console.log('Port check passed')
}
For invalid configuration, the error message explains the cause and exitCode = 1 reports failure to the caller. The success branch does not set a failure code, so normal completion returns 0.
Let the terminal decide whether to continue
In a macOS/Linux terminal or PowerShell 7, run:
node --env-file=.env check-port.mjs && echo "Proceed to the next step"
The command after && runs only if the preceding command succeeds. echo makes it easy to see whether the next step runs. In a real project, replace it with a service startup or build command.
.env contents | Check script exit code | Terminal result |
|---|---|---|
PORT=3000 | 0 | Prints “Port check passed”, then “Proceed to the next step” |
PORT=abc | 1 | Prints the port error and skips echo |
If you remove process.exitCode = 1 from the failure branch, the script ends normally even after printing an error, and the next command still runs. Exit codes let other tools detect failure, rather than only showing an error to a person.
Inspect the script's exit code separately
In a macOS/Linux terminal, run these commands in sequence:
node --env-file=.env check-port.mjs
echo $?
In PowerShell, including Windows PowerShell 5.1, which does not support &&, run:
node --env-file=.env check-port.mjs
$LASTEXITCODE
With PORT=abc, the exit code is 1; after restoring PORT=3000, it is 0. Do not insert another command before inspecting the code, or you may read that command's result instead.
exitCode does not stop the current code
Setting exitCode only records the eventual status; subsequent JavaScript still runs. The example therefore separates failure and success with if/else. Inside a function, you can also set it and then return to end the current task.
process.exit(1) terminates the process immediately and may truncate pending asynchronous output. Short validation scripts usually set exitCode and end naturally. Programs with network connections or repeating timers must also close those resources; setting an exit code alone does not stop them.
⚠️ Unhandled errors can terminate the program
With Node.js 24's default configuration and no process-level handlers taking over, uncaught exceptions and unhandled Promise rejections report errors and terminate the process with a failure status. Fix handling in the failing file operation, asynchronous task, or event listener rather than ignoring the error and continuing.
You may encounter uncaughtException, meaning an exception was not caught, and unhandledRejection, meaning a Promise rejection was not handled in time. These are process-level notifications, not ways to recover application logic. Registering listeners changes default failure handling; do not add empty listeners just to suppress errors.
❓ Questions and answers
Q1: How do I choose between arguments and environment variables?
Use arguments for inputs specific to one run, such as a filename. Use environment variables for deployment configuration.
Q2: Why does the program keep running after setting exitCode?
Timers, network connections, or other active work may remain. Setting an exit code does not close them.
Q3: Does changing process.env change the parent terminal?
No. It affects the current process environment and the environment inherited by default by child processes it starts afterward.
🧪 Exercise
Run the port check with both PORT=abc and PORT=3000, verifying the exit code and whether the next command runs. Temporarily comment out the exitCode assignment and observe why printing an error does not replace reporting failure.
// Write your code here
🎉 Try these techniques with your own examples!
