-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
116 lines (102 loc) · 3.91 KB
/
server.js
File metadata and controls
116 lines (102 loc) · 3.91 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
const express = require('express');
const path = require('path');
const sqlite3 = require('sqlite3').verbose();
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware to parse JSON
app.use(express.json());
// Serve static files from the current directory
app.use(express.static(__dirname));
// Initialize SQLite database
const db = new sqlite3.Database('./clickcount.db', (err) => {
if (err) {
console.error('Error opening database:', err.message);
} else {
console.log('✅ Connected to SQLite database');
// Create clicks table if it doesn't exist
db.run(`CREATE TABLE IF NOT EXISTS clicks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
count INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)`, (err) => {
if (err) {
console.error('Error creating table:', err.message);
} else {
console.log('✅ Database table ready');
// Initialize with count 0 if no records exist
db.get('SELECT COUNT(*) as count FROM clicks', (err, row) => {
if (err) {
console.error('Error checking records:', err.message);
} else if (row.count === 0) {
db.run('INSERT INTO clicks (count) VALUES (0)', (err) => {
if (err) {
console.error('Error initializing count:', err.message);
} else {
console.log('✅ Initialized click count to 0');
}
});
}
});
}
});
}
});
// Route for the main page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// API route to get current click count
app.get('/api/click-count', (req, res) => {
db.get('SELECT count FROM clicks ORDER BY id DESC LIMIT 1', (err, row) => {
if (err) {
console.error('Error getting click count:', err.message);
res.status(500).json({ error: 'Failed to get click count' });
} else {
res.json({ count: row ? row.count : 0 });
}
});
});
// API route to increment click count
app.post('/api/click', (req, res) => {
db.get('SELECT count FROM clicks ORDER BY id DESC LIMIT 1', (err, row) => {
if (err) {
console.error('Error getting current count:', err.message);
res.status(500).json({ error: 'Failed to get current count' });
return;
}
const currentCount = row ? row.count : 0;
const newCount = currentCount + 1;
db.run('INSERT INTO clicks (count) VALUES (?)', [newCount], function(err) {
if (err) {
console.error('Error updating click count:', err.message);
res.status(500).json({ error: 'Failed to update click count' });
} else {
console.log(`✅ Click count updated to ${newCount}`);
res.json({ count: newCount });
}
});
});
});
// Handle 404 errors
app.use((req, res) => {
res.status(404).sendFile(path.join(__dirname, 'index.html'));
});
// Start the server
app.listen(PORT, () => {
console.log(`🚀 Server is running on http://localhost:${PORT}`);
console.log(`📁 Serving files from: ${__dirname}`);
console.log(`🌐 Open your browser and visit: http://localhost:${PORT}`);
});
// Graceful shutdown
process.on('SIGINT', () => {
console.log('\n🛑 Shutting down server...');
db.close((err) => {
if (err) {
console.error('Error closing database:', err.message);
} else {
console.log('✅ Database connection closed');
}
process.exit(0);
});
});