-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
61 lines (52 loc) · 2 KB
/
server.mjs
File metadata and controls
61 lines (52 loc) · 2 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
import { createServer } from 'http';
import { readdirSync, readFile, readFileSync, existsSync, lstatSync } from 'fs';
import path from 'path';
const routes = readdirSync('src')
.filter(f => f.endsWith('.mjs'))
.reduce((map, file) => {
const route = file === 'index.mjs' ? '/' : '/' + file.replace('.mjs', '');
map[route] = path.join('src', file);
return map;
}, {});
Object.entries(routes).forEach(([url, file]) => { console.log(`\t${file} → ${url}`) });
const server = createServer(async (req, res) => {
if (req.url.startsWith('/api')) {
const route = req.url.replace('/api', '') || '/';
const page = routes[route];
if (page) {
try {
const webPath = '/' + path.relative('.', page).replace(/\\/g, '/');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(webPath);
} catch (err) {
console.error(err);
res.writeHead(500).end('Failed to load page');
}
} else {
res.writeHead(404).end('Page Not Found');
}
return;
}
const filePath = path.join('.', req.url);
if (existsSync(filePath) && lstatSync(filePath).isFile()) {
const ext = path.extname(filePath);
const contentType = {
'.js': 'application/javascript',
'.mjs': 'application/javascript',
'.css': 'text/css',
'.html': 'text/html',
}[ext] || 'text/plain';
const content = readFileSync(filePath);
res.writeHead(200, { 'Content-Type': contentType });
return res.end(content);
}
// Serve static index.html for all paths
readFile(path.join('index.html'), (err, content) => {
if (err) return res.writeHead(500).end('Error loading index');
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content);
});
});
server.listen(3000, () => {
console.log('\nmini-framework running on http://localhost:3000');
});