Working with Process Object

1. Accessing Command-Line Arguments

Example: process.argv

// node script.js --port 3000 file.txt
console.log(process.argv);
// [ "/usr/bin/node", "/abs/script.js", "--port", "3000", "file.txt" ]
const args = process.argv.slice(2);
IndexValue
0Path to node
1Path to script
2+User args

2. Reading Environment Variables

SnippetDescription
process.env.NODE_ENVRead string (or undefined)
process.env.PORT ?? 3000Default with nullish coalescing
process.env.FLAG = "1"Always coerced to string

3. Getting Current Directory (process.cwd)

APIReturns
process.cwd()Where node was launched
__dirname / import.meta.dirnameWhere the file is

4. Changing Directory (process.chdir)

Example

process.chdir("/tmp");
console.log(process.cwd()); // "/tmp"
Warning: Avoid in libraries — affects entire process.

5. Getting Platform Info

PropertySample Value
process.platformdarwin, linux, win32
process.archx64, arm64
process.versionv20.11.1
process.versionsObject with v8, openssl, …
process.releaseLTS info

6. Getting Process ID (process.pid)

APIReturns
process.pidCurrent PID
process.ppidParent PID

7. Accessing Memory Usage (process.memoryUsage)

FieldMeaning
rssResident set size (bytes)
heapTotalV8 heap allocated
heapUsedV8 heap in use
externalOff-heap C++ objects
arrayBuffersArrayBuffer/Buffer bytes

8. Getting CPU Usage (process.cpuUsage)

Example

const start = process.cpuUsage();
heavyWork();
const diff = process.cpuUsage(start); // { user, system } in microseconds

9. Measuring Performance (process.hrtime, process.hrtime.bigint)

APIReturns
process.hrtime()[seconds, nanoseconds] tuple
process.hrtime.bigint()BigInt nanoseconds (preferred)
performance.now()Float ms (Web API)

10. Handling Process Events

EventFires When
exitEvent loop drained or process.exit()
beforeExitLoop empty, can schedule async work
uncaughtExceptionSync error not caught
unhandledRejectionPromise rejection w/o handler
warningProcess warning emitted
SIGINT / SIGTERMOS signals
messageIPC message from parent

11. Exiting Process (process.exit)

CodeMeaning
0Success
1Generic error
process.exitCode = 1Set without forcing exit (preferred)
Warning: process.exit() aborts pending I/O. Prefer setting exitCode and letting the loop drain.

12. Sending Process Signals (process.kill)

CallEffect
process.kill(pid, "SIGTERM")Polite shutdown
process.kill(pid, "SIGKILL")Force kill
process.kill(pid, 0)Existence test (no signal)