-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
105 lines (92 loc) · 2.73 KB
/
server.js
File metadata and controls
105 lines (92 loc) · 2.73 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 5000;
const HOST = '0.0.0.0';
// MIME types for different file extensions
const mimeTypes = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.json': 'application/json'
};
const server = http.createServer((req, res) => {
// Parse URL and remove query params
let filePath = req.url.split('?')[0];
// Default to index.html for root
if (filePath === '/') {
filePath = '/index.html';
}
// Remove leading slash and resolve path
const fullPath = path.join(__dirname, filePath.substring(1));
// Get file extension
const ext = path.extname(fullPath).toLowerCase();
const contentType = mimeTypes[ext] || 'text/plain';
// Check if file exists
fs.access(fullPath, fs.constants.F_OK, (err) => {
if (err) {
// File not found - try serving index.html for SPA routing
const indexPath = path.join(__dirname, 'index.html');
fs.readFile(indexPath, (err, content) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
} else {
res.writeHead(200, {
'Content-Type': 'text/html',
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
});
res.end(content);
}
});
return;
}
// File exists, serve it
fs.readFile(fullPath, (err, content) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('500 Internal Server Error');
return;
}
// Set headers with cache control
res.writeHead(200, {
'Content-Type': contentType,
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
});
res.end(content);
});
});
});
server.listen(PORT, HOST, () => {
console.log(`Marcus Savings Tracker server running at http://${HOST}:${PORT}/`);
console.log('Serving static files with cache disabled for development');
});
// Handle server errors
server.on('error', (err) => {
console.error('Server error:', err);
});
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('Received SIGTERM, shutting down gracefully');
server.close(() => {
console.log('Server closed');
process.exit(0);
});
});
process.on('SIGINT', () => {
console.log('Received SIGINT, shutting down gracefully');
server.close(() => {
console.log('Server closed');
process.exit(0);
});
});