NodeJS by Example: Process Object
|
The process object is a global that provides information about and control over the current Node.js process. It's available without importing. |
|
|
Environment Variables Access environment variables through process.env. Set environment variables (only affects current process) Common pattern: provide defaults |
|
|
Command Line Arguments process.argv is an array containing command line arguments. [0] = path to node executable [1] = path to script [2+] = user arguments Parse arguments Simple flag parsing |
|
|
Current Working Directory Get and change the current working directory. Change directory process.chdir('/tmp'); console.log('New CWD:', process.cwd()); |
|
|
Process Information Access information about the running process. |
|
|
Memory Usage Get memory usage statistics. |
|
|
CPU Usage Get CPU usage since process start or last call. ... do some work ... |
|
|
Uptime Get process uptime in seconds. |
|
|
Exit Codes Exit the process with a status code. process.exit(0); // Success process.exit(1); // General error Set exit code without immediately exiting Listen for exit event (can't do async work here) |
|
|
Uncaught Exceptions Handle uncaught exceptions (use sparingly - prefer proper error handling). Unhandled promise rejections |
|
|
Signals Handle operating system signals. Send signals to other processes process.kill(pid, 'SIGTERM'); |
|
|
Standard I/O Streams process provides stdin, stdout, and stderr streams. Read from stdin process.stdin.on('data', (data) => { console.log('Input:', data.toString()); }); |
|
|
Next Tick Schedule a callback to run before the next event loop iteration. Output: "This runs first" then "This runs before any I/O events" |
|
|
High Resolution Time Get high-resolution time for precise measurements. ... do something ... |
|
|
Report Generate diagnostic reports. process.report.writeReport('./report.json'); console.log('Report directory:', process.report.directory); |
|
|
Practical Example: CLI Application A pattern for building command-line applications. Usage Example: node script.js --name test -v file.txt Options: { name: 'test', v: true } Positional: ['file.txt'] |
|
|
Run with environment variable |
|
|
Run with command line arguments |
|
|
Check process info |
|