The process
Module
The process
module provides a way to interact with the current Node.js process. It enables developers to access environment variables, manage inputs/outputs, and control the process's lifecycle.
Key Features
Accessing Environment Variables
Use process.env
to retrieve environment-specific variables.
console.log('Database Host:', process.env.DB_HOST);
Exiting the Process
You can terminate the process with process.exit()
.
if (error) {
console.error('Critical error occurred. Exiting...');
process.exit(1); // Non-zero exit code indicates an error
}
Listening to Process Events
The process
object emits various events like exit
, uncaughtException
, and SIGINT
.
process.on('exit', code => {
console.log(`Process exiting with code: ${code}`);
});
process.on('uncaughtException', err => {
console.error('Unhandled exception:', err);
});
Standard Input and Output
Interact with the terminal using process.stdin
and process.stdout
.
process.stdin.on('data', data => {
console.log(`You entered: ${data.toString()}`);
});
The cluster
Module
The cluster
module enables you to create child processes (workers) that share the same server port. This is useful for taking advantage of multi-core CPUs to improve performance and scalability.
Key Concepts
- Master Process: Responsible for spawning and managing worker processes.
- Worker Processes: Execute application logic and communicate with the master process.
Basic Usage
The following example demonstrates how to use the cluster
module to create a simple application.
Master Process
const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
const numCPUs = os.cpus().length;
console.log(`Master process running with PID: ${process.pid}`);
// Fork workers for each CPU core
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} exited with code ${code}`);
});
} else {
require('./server'); // Worker runs the application logic
}
Worker Process
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200);
res.end(`Handled by worker with PID: ${process.pid}`);
}).listen(8000);
console.log(`Worker process running with PID: ${process.pid}`);
Benefits of Clustering
- Improved Performance: Utilizes multiple CPU cores effectively.
- Fault Tolerance: If a worker crashes, the master process can spawn a new one.
- Load Balancing: Distributes incoming connections across workers.
Comparing process
and cluster
Modules
Feature | process Module | cluster Module |
---|---|---|
Focus | Interacting with the Node.js process | Scaling applications using multiple processes |
Event Handling | Handles events like exit and SIGINT | Manages worker lifecycle events |
Communication Mechanism | Streams and environment variables | IPC (Inter-Process Communication) |
Use Case | Process control and environment config | Performance scaling for multi-core CPUs |
Best Practices
1. Graceful Shutdown: Ensure processes close connections and release resources before exiting.
process.on('SIGTERM', () => {
console.log('Shutting down gracefully...');
server.close(() => process.exit(0));
});
2. Error Handling: Catch unhandled exceptions in both master and worker processes.
3. Monitor Workers: Implement monitoring tools to restart crashed workers automatically.
4. Limit Resource Usage: Avoid memory leaks and optimize CPU utilization.
By leveraging the process
and cluster
modules, Node.js developers can build robust and efficient applications capable of handling complex operations and scaling seamlessly in multi-core environments. Understanding these modules is essential for designing high-performance Node.js systems.
About Lavesh Katariya
Innovative Full-Stack Developer | Technical Team Lead | Cloud Solutions Architect
With over a decade of experience in building and leading cutting-edge web application projects, I specialize in developing scalable, high-performance platforms that drive business growth. My expertise spans both front-end and back-end development, making me a versatile and hands-on leader capable of delivering end-to-end solutions.