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);
| Index | Value |
| 0 | Path to node |
| 1 | Path to script |
| 2+ | User args |
2. Reading Environment Variables
| Snippet | Description |
process.env.NODE_ENV | Read string (or undefined) |
process.env.PORT ?? 3000 | Default with nullish coalescing |
process.env.FLAG = "1" | Always coerced to string |
3. Getting Current Directory (process.cwd)
| API | Returns |
process.cwd() | Where node was launched |
__dirname / import.meta.dirname | Where the file is |
4. Changing Directory (process.chdir)
Example
process.chdir("/tmp");
console.log(process.cwd()); // "/tmp"
Warning: Avoid in libraries — affects entire process.
| Property | Sample Value |
process.platform | darwin, linux, win32 |
process.arch | x64, arm64 |
process.version | v20.11.1 |
process.versions | Object with v8, openssl, … |
process.release | LTS info |
6. Getting Process ID (process.pid)
| API | Returns |
process.pid | Current PID |
process.ppid | Parent PID |
7. Accessing Memory Usage (process.memoryUsage)
| Field | Meaning |
rss | Resident set size (bytes) |
heapTotal | V8 heap allocated |
heapUsed | V8 heap in use |
external | Off-heap C++ objects |
arrayBuffers | ArrayBuffer/Buffer bytes |
8. Getting CPU Usage (process.cpuUsage)
Example
const start = process.cpuUsage();
heavyWork();
const diff = process.cpuUsage(start); // { user, system } in microseconds
| API | Returns |
process.hrtime() | [seconds, nanoseconds] tuple |
process.hrtime.bigint() | BigInt nanoseconds (preferred) |
performance.now() | Float ms (Web API) |
10. Handling Process Events
| Event | Fires When |
exit | Event loop drained or process.exit() |
beforeExit | Loop empty, can schedule async work |
uncaughtException | Sync error not caught |
unhandledRejection | Promise rejection w/o handler |
warning | Process warning emitted |
SIGINT / SIGTERM | OS signals |
message | IPC message from parent |
11. Exiting Process (process.exit)
| Code | Meaning |
0 | Success |
1 | Generic error |
process.exitCode = 1 | Set 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)
| Call | Effect |
process.kill(pid, "SIGTERM") | Polite shutdown |
process.kill(pid, "SIGKILL") | Force kill |
process.kill(pid, 0) | Existence test (no signal) |