WeightTracker/server.js

60 lines
1.6 KiB
JavaScript

const http = require('http');
const fs = require('fs');
const path = require('path');
// Port can be specified as command line argument or default to 8080
const port = process.argv[2] || 8080;
// MIME types for different file extensions
const mimeTypes = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon'
};
// Create a simple HTTP server
const server = http.createServer((req, res) => {
console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
// Handle root path
let filePath = req.url === '/'
? path.join(__dirname, 'index.html')
: path.join(__dirname, req.url);
// Get the file extension
const extname = path.extname(filePath);
// Default content type
let contentType = mimeTypes[extname] || 'application/octet-stream';
// Read file and serve content
fs.readFile(filePath, (error, content) => {
if (error) {
if (error.code === 'ENOENT') {
// File not found
res.writeHead(404);
res.end('404 - File Not Found');
} else {
// Server error
res.writeHead(500);
res.end(`Server Error: ${error.code}`);
}
} else {
// Successful response
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
// Start the server
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
console.log(`Press Ctrl+C to stop the server`);
});