-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevserver.js
More file actions
43 lines (38 loc) · 1.37 KB
/
devserver.js
File metadata and controls
43 lines (38 loc) · 1.37 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
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { join, extname } from 'node:path';
const MIME = {
'.html': 'text/html',
'.js': 'application/javascript',
'.mjs': 'application/javascript',
'.css': 'text/css',
'.json': 'application/json',
};
const server = createServer(async (req, res) => {
const url = req.url.split('?')[0];
const filePath = url.startsWith('/dist/') || url.startsWith('/node_modules/')
? join(process.cwd(), url)
: join(process.cwd(), 'app', url === '/' ? '/index.html' : url);
try {
const data = await readFile(filePath);
const mime = MIME[extname(filePath)] ?? 'text/plain';
res.writeHead(200, { 'Content-Type': mime });
res.end(data);
} catch {
// SPA fallback solo para rutas sin extensión (history mode)
if (extname(url) === '') {
try {
const data = await readFile(join(process.cwd(), 'app', 'index.html'));
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
} catch {
res.writeHead(404);
res.end('Not found');
}
} else {
res.writeHead(404);
res.end('Not found');
}
}
});
server.listen(3000, () => console.log('Dev server: http://localhost:3000'));