Node.js Process & Environment
Every running Node.js program is an operating-system process. The global process object is your window onto it: command-line arguments, environment variables, the working directory, standard input/output, the exit code, signals and memory usage. You don't need to import it, although import process from 'node:process' makes the dependency explicit.
Command-line arguments
process.argv is an array of strings. The first two entries are the path of the node executable and the path of your script; your own arguments start at index 2.
// greet.js
const [name = 'world', times = '1'] = process.argv.slice(2);
for (let i = 0; i < Number(times); i++) console.log(`Hello, ${name}!`);$ node greet.js Ana 2
Hello, Ana!
Hello, Ana!For real tools, util.parseArgs() parses flags like --verbose and -n 3 for you. It accepts an args array, so we can try it without a terminal:
const { parseArgs } = require('node:util');
const { values, positionals } = parseArgs({
args: ['report.csv', '--limit', '5', '-v', '--format=json'],
options: {
limit: { type: 'string', default: '10' },
verbose: { type: 'boolean', short: 'v', default: false },
format: { type: 'string' },
},
allowPositionals: true,
});
console.log(values);
console.log(positionals);
console.log('argv starts at index 2:', process.argv.slice(2));[Object: null prototype] { limit: '5', verbose: true, format: 'json' }
[ 'report.csv' ]
argv starts at index 2: []
The playground was started without extra arguments, so process.argv.slice(2) is empty.
Environment variables
process.env holds the environment variables as strings. They are the standard way to configure an app without changing its code: port numbers, database URLs, API keys, NODE_ENV.
process.env.APP_PORT = '8080'; // normally set by the shell
process.env.DEBUG_SQL = 'false';
const port = Number(process.env.APP_PORT ?? 3000);
const host = process.env.APP_HOST ?? 'localhost';
const debugSql = process.env.DEBUG_SQL === 'true';
console.log(port, typeof port);
console.log(host);
console.log(debugSql);
process.env.COUNT = 5; // converted to a string!
console.log(typeof process.env.COUNT);
delete process.env.COUNT;
console.log(process.env.COUNT);8080 number
localhost
false
string
undefined
Note:
'false'is a non-empty string, soif (process.env.DEBUG_SQL)would be true. Always compare with=== 'true'or convert explicitly.
Set variables when starting the program (Linux/macOS syntax), or load them from a .env file with the built-in --env-file flag (Node 20.6+):
$ APP_PORT=4000 node -e "console.log(process.env.APP_PORT)"
4000
$ printf 'GREETING=Xin chào\n' > .env
$ node --env-file=.env -e "console.log(process.env.GREETING)"
Xin chàoInformation about the process
| Property / method | Value |
|---|---|
process.version |
Node version, e.g. 'v24.15.0' |
process.versions |
versions of Node, V8, OpenSSL… |
process.platform / process.arch |
'linux', 'x64', … |
process.pid |
process ID |
process.cwd() |
current working directory |
process.chdir(dir) |
change the working directory |
process.uptime() |
seconds since the process started |
process.memoryUsage() |
heap and RSS usage in bytes |
process.hrtime.bigint() |
high-resolution timer in nanoseconds |
These values differ on every machine and run, so the playground only checks their types:
console.log(process.version.startsWith('v'));
console.log(typeof process.pid, typeof process.cwd(), typeof process.uptime());
console.log(Object.keys(process.memoryUsage()));
console.log(typeof process.hrtime.bigint());true
number string number
[ 'rss', 'heapTotal', 'heapUsed', 'external', 'arrayBuffers' ]
bigint
Standard streams
process.stdout and process.stderr are writable streams; process.stdin is readable. console.log() writes to stdout and console.error() to stderr. Use process.stdout.write() when you don't want an automatic newline:
process.stdout.write('Loading');
for (let i = 0; i < 3; i++) process.stdout.write('.');
process.stdout.write(' done\n');Loading... done
Keep errors and diagnostics on stderr: when a user redirects your program's output with node app.js > out.txt, the file receives only stdout, while console.error() messages still appear in the terminal.
Exit codes and events
A process ends with an exit code: 0 means success, anything else means failure. Scripts, CI pipelines and Docker rely on it.
process.on('exit', (code) => {
console.log('exiting with code', code);
});
function validate(config) {
if (!config.url) {
console.log('missing url');
process.exitCode = 1; // finish normally, but report failure
return;
}
console.log('config ok');
}
validate({ url: 'https://example.com' });
validate({});
process.exitCode = 0; // reset so this example counts as successfulconfig ok
missing url
exiting with code 0
| Way to stop | Behaviour |
|---|---|
| let the program finish | exits when no work is left (timers, sockets…) |
process.exitCode = 1 |
sets the code, lets pending work finish — preferred |
process.exit(1) |
stops immediately; pending writes may be lost |
process.on('SIGINT', fn) |
handle Ctrl+C yourself, e.g. to close a server gracefully |
Test yourself
Which index of process.argv holds the first user argument?
- 0
- 1
- 2
- 3
DEBUG=false node app.js — what is Boolean(process.env.DEBUG)?
falsetrueundefined- It throws
Why is process.exitCode = 1 usually better than process.exit(1)?
- It's faster
- It lets pending output and cleanup finish
- It restarts the process
- It hides the error