-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
71 lines (54 loc) · 1.66 KB
/
server.js
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
// Import necessary modules
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const socket = require("socket.io");
const bodyParser = require("body-parser");
const userRoutes = require("./models/user"); // Import the user route file
const config = require("./config/db");
const routes = require("./routes/userRoutes");
// Initialize Express
mongoose.Promise = global.Promise;
// Connect to the database
mongoose.connect(config.db);
let db = mongoose.connection;
db.on("open", () => {
console.log("Connected to the database.");
});
db.on("error", (err) => {
console.log(`Database error: ${err}`);
});
// Instantiate express
const app = express();
// Set public folder using built-in express.static middleware
app.use(express.static("public"));
// Set body parser middleware
app.use(bodyParser.json());
if (process.env.CORS) {
app.use(cors());
}
app.use((err, req, res, next) => {
if (res.headersSent) return next(err);
res.status(400).json({ err: err });
});
// Use the userRoutes for handling user-related routes
app.use("/api/users", require("./routes/userRoutes"));
// Start the server
const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
const io = socket(server);
let online = 0;
io.on("connection", (socket) => {
online++;
console.log(`Socket ${socket.id} connected.`);
console.log(`Online: ${online}`);
io.emit("visitor enters", online);
socket.on("disconnect", () => {
online--;
console.log(`Socket ${socket.id} disconnected.`);
console.log(`Online: ${online}`);
io.emit("visitor exits", online);
});
});