timesite/server.js
2025-07-14 18:43:59 -07:00

67 lines
2.0 KiB
JavaScript

const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 8080;
// MIME types
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json'
};
// Create server
const server = http.createServer((req, res) => {
// CORS headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'GET' && req.url === '/api/time') {
// API endpoint for time
const now = new Date();
const epochNanoseconds = BigInt(now.getTime()) * BigInt(1000000);
const payload = {
utc_epoch_nanoseconds: epochNanoseconds.toString(),
utc_epoch_milliseconds: now.getTime(),
iso_string: now.toISOString()
};
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(payload));
} else if (req.method === 'GET' || req.method === 'HEAD') {
// Serve static files
let filePath = '.' + req.url;
if (filePath === './') {
filePath = './index.html';
}
const extname = path.extname(filePath);
const contentType = mimeTypes[extname] || 'text/plain';
fs.readFile(filePath, (error, content) => {
if (error) {
if (error.code === 'ENOENT') {
res.writeHead(404);
res.end('File not found');
} else {
res.writeHead(500);
res.end('Server error: ' + error.code);
}
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content);
}
});
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});