Node.js Process Management
Node.js Process Management
Process management refers to how Node.js handles:
-
The running process
-
Environment variables
-
Process information
-
Exiting the app
-
Managing multiple worker processes
-
Background/production process managers (PM2, Forever, Nodemon)
Node.js exposes process-related features through the global process object and external tools.
✅ 1. The process Object
process is a global object that provides information and control over the current Node.js process.
No import needed.
📌 2. Getting Process Information
Process ID
Platform
Node version
Working directory
Memory usage
📌 3. Environment Variables (process.env)
Used for configuration and secrets.
Example:
In Node:
📌 4. Access Command-Line Arguments
Example:
Output:
📌 5. Exiting the Process
Normal Exit:
Exit With Code:
Exit codes:
-
0 → success
-
1 → error
📌 6. Process Events
on exit
on uncaughtException
on unhandled promise rejection
📌 7. Process.nextTick()
Executes a callback before the event loop continues.
📌 8. High-Level Process Management: Clustering
Node.js is single-threaded, but you can use child processes or the cluster module to use all CPU cores.
Example (Cluster):
📌 9. Child Processes (Multiple Processes)
Child processes allow running external commands or multiple Node programs.
📌 10. Running Node Apps in Production (PM2)
PM2 is the most used Node process manager.
Install:
Start app:
View running processes:
Restart:
Stop:
Monitor:
PM2 ensures:
-
Auto-restart on crash
-
Load balancing
-
Log management
-
Daemon mode
📌 11. Other Process Managers
Nodemon (for dev auto-restart)
Forever (older tool)
⭐ Summary
| Feature | Description |
|---|---|
process object |
Controls Node process |
| env variables | Store config/secrets |
| argv | CLI arguments |
| exit codes | Success/error exits |
| process events | Handle crashes & exit |
| nextTick | Microtask scheduling |
| clusters | Multi-core usage |
| child processes | Execute external apps |
| PM2 | Best production process manager |
| Nodemon | Dev auto-reload |
