Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.1 kB
2
Indexable
Never
const cluster = require('cluster');
const os = require('os');
const app = require('./config/server');

// Number of CPU cores
const numCPUs = os.cpus().length;

// If the current process is the master process
if (cluster.isMaster) {
    console.log(`Master ${process.pid} is running`);

    // Fork workers for each CPU core
    for (let i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    // Handle worker process exit
    cluster.on('exit', (worker, code, signal) => {
        console.log(`Worker ${worker.process.pid} died`);
        // Ensure a new worker is spawned if one dies
        cluster.fork();
    });
} else {
    // Worker process - start the server
    const startServer = async () => {
        try {
            const PORT = process.env.PORT || 5000;
            await app.listen(PORT);
            console.log(`Worker ${process.pid} is running on port ${PORT}`);
        } catch (error) {
            console.error(`Worker ${process.pid} encountered an error:`, error.message);
            process.exit(1);
        }
    };

    startServer();
}

Leave a Comment