1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| require('dotenv').config(); const express = require('express'); const ws = require('ws'); const http = require('http'); const multer = require('multer'); const mongoose = require('mongoose'); const helmet = require('helmet'); const morgan = require('morgan'); const cluster = require('cluster'); const os = require('os'); const compression = require('compression'); const fs = require('fs'); const path = require('path');
const PORT = process.env.PORT || 8080; const MONGO_URI = process.env.MONGO_URI; const NUM_CPUS = os.cpus().length;
if (cluster.isMaster) { console.log(`Master process is running. Spawning ${NUM_CPUS} workers...`); for (let i = 0; i < NUM_CPUS; i++) { cluster.fork(); }
cluster.on('exit', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} died. Spawning a new worker.`); cluster.fork(); }); } else { const app = express(); const server = http.createServer(app); const wss = new ws.Server({ server });
mongoose.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch(err => console.error('MongoDB connection error:', err));
app.use(express.json()); app.use(helmet()); app.use(morgan('common')); app.use(compression());
const upload = multer({ dest: 'uploads/' });
app.use(express.static(path.join(__dirname, 'public')));
app.use((req, res, next) => { console.log(`Received ${req.method} request for ${req.url}`); next(); });
wss.on('connection', (socket) => { console.log('WebSocket connection established.'); socket.on('message', (message) => { console.log(`Received WebSocket message: ${message}`); socket.send(`Message received: ${message}`); }); });
app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'public', 'index.html')); });
app.get('/api/data', async (req, res) => { res.json({ message: 'Server API Response', data: [] }); });
app.post('/upload', upload.single('file'), (req, res) => { console.log('File uploaded:', req.file); res.status(201).json({ message: 'File uploaded successfully', file: req.file }); });
app.get('/greet/:name', (req, res) => { const name = req.params.name || 'stranger'; res.send(`<h1>Hello, ${name}!</h1>`); });
app.use((req, res, next) => { res.status(404).sendFile(path.join(__dirname, 'public', '404.html')); });
app.use((err, req, res, next) => { console.error('Error encountered:', err); res.status(500).json({ error: 'An internal server error occurred' }); });
server.listen(PORT, () => { console.log(`Worker process ${process.pid} is running on port ${PORT}`); }); }
|