Topic 29 of 55
Process Object
Overview
The `process` object is a global variable that provides information about, and control over, the current Node.js process. It's essential for reading environment variables, managing application lifecycle, and reading command line arguments.
Syntax
javascript
// The process object is available everywhere
console.log(process.pid); // Process ID (useful for killing tasks)
console.log(process.version); // Node.js version string
console.log(process.platform); // 'darwin' (Mac), 'win32' (Windows), 'linux'
console.log(process.cwd()); // Current Working Directory
// Exit the application programmatically
// 0 means success, any non-zero number means failure/error
if (databaseConnectionFailed) {
console.error("Fatal error!");
process.exit(1);
}Common Pitfalls
- Calling `process.exit()` forces the process to terminate immediately, aborting any asynchronous operations that are still pending (like saving a file or sending an HTTP response).
- `process.cwd()` is where the script was CALLED from, whereas `__dirname` is where the script FILE actually lives. They can be different!
Real-World Example
Measuring memory usage and application uptime:
example
javascript
// Get memory statistics
const memoryUsage = process.memoryUsage();
console.log(`Memory used: ${Math.round(memoryUsage.heapUsed / 1024 / 1024)} MB`);
// Get application uptime in seconds
console.log(`App has been running for ${process.uptime()} seconds`);
// Listen for the application exiting to do cleanup (like closing DB connections)
process.on('exit', (code) => {
console.log(`About to exit with code: ${code}`);
});