82 lines
2.1 KiB
JavaScript
82 lines
2.1 KiB
JavaScript
const http = require('http');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
const PORT = 8080;
|
|
|
|
const MIME_TYPES = {
|
|
'.html': 'text/html',
|
|
'.js': 'text/javascript',
|
|
'.css': 'text/css',
|
|
'.json': 'application/json',
|
|
'.wasm': 'application/wasm',
|
|
'.png': 'image/png',
|
|
'.jpg': 'image/jpg',
|
|
'.gif': 'image/gif',
|
|
'.svg': 'image/svg+xml',
|
|
'.ico': 'image/x-icon',
|
|
'.txt': 'text/plain',
|
|
};
|
|
|
|
const server = http.createServer((req, res) => {
|
|
console.log(`${req.method} ${req.url}`);
|
|
|
|
// Handle CORS preflight requests
|
|
if (req.method === 'OPTIONS') {
|
|
res.writeHead(204, {
|
|
'Access-Control-Allow-Origin': '*',
|
|
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
|
'Access-Control-Allow-Headers': 'Content-Type',
|
|
});
|
|
res.end();
|
|
return;
|
|
}
|
|
|
|
// Normalize URL path
|
|
let filePath = req.url;
|
|
if (filePath === '/' || filePath === '') {
|
|
filePath = '/index.html';
|
|
}
|
|
|
|
// Determine the file path
|
|
const resolvedPath = path.resolve(
|
|
__dirname,
|
|
filePath.startsWith('/pkg/')
|
|
? `..${filePath}` // For files in the pkg directory (one level up)
|
|
: `.${filePath}` // For files in the www directory
|
|
);
|
|
|
|
// Get the file extension
|
|
const extname = path.extname(resolvedPath);
|
|
const contentType = MIME_TYPES[extname] || 'application/octet-stream';
|
|
|
|
// Read and serve the file
|
|
fs.readFile(resolvedPath, (err, data) => {
|
|
if (err) {
|
|
if (err.code === 'ENOENT') {
|
|
console.error(`File not found: ${resolvedPath}`);
|
|
res.writeHead(404);
|
|
res.end('File not found');
|
|
} else {
|
|
console.error(`Server error: ${err}`);
|
|
res.writeHead(500);
|
|
res.end(`Server Error: ${err.code}`);
|
|
}
|
|
return;
|
|
}
|
|
|
|
// Set CORS headers for all responses
|
|
res.writeHead(200, {
|
|
'Content-Type': contentType,
|
|
'Access-Control-Allow-Origin': '*',
|
|
'Cross-Origin-Embedder-Policy': 'require-corp',
|
|
'Cross-Origin-Opener-Policy': 'same-origin',
|
|
});
|
|
res.end(data);
|
|
});
|
|
});
|
|
|
|
server.listen(PORT, () => {
|
|
console.log(`Server running at http://localhost:${PORT}/`);
|
|
console.log(`Press Ctrl+C to stop the server`);
|
|
}); |