-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
72 lines (61 loc) · 1.94 KB
/
Copy pathserver.js
File metadata and controls
72 lines (61 loc) · 1.94 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
62
63
64
65
66
67
68
69
70
71
72
const http = require('http');
const fs = require('fs');
const path = require('path');
const ROOT = __dirname;
const PORT = Number(process.env.PORT || 4174);
const TYPES = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.png': 'image/png',
'.webp': 'image/webp',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.svg': 'image/svg+xml; charset=utf-8',
'.ico': 'image/x-icon',
};
function send(res, status, body, type = 'text/plain; charset=utf-8') {
res.writeHead(status, { 'Content-Type': type });
res.end(body);
}
function safePath(urlPath) {
const clean = decodeURIComponent(urlPath.split('?')[0]);
const requested = clean === '/' ? '/index.html' : clean;
const file = path.normalize(path.join(ROOT, requested));
return file.startsWith(ROOT) ? file : null;
}
async function handleApi(req, res) {
const chunks = [];
req.on('data', chunk => chunks.push(chunk));
req.on('end', () => {
if (req.url.startsWith('/api/claim') && req.method === 'POST') {
send(res, 200, JSON.stringify({ ok: true, status: 'TBD' }), 'application/json; charset=utf-8');
return;
}
send(res, 404, JSON.stringify({ error: 'API route TBD' }), 'application/json; charset=utf-8');
});
}
const server = http.createServer((req, res) => {
if (req.url.startsWith('/api/')) {
handleApi(req, res);
return;
}
const file = safePath(req.url);
if (!file) {
send(res, 403, 'Forbidden');
return;
}
fs.stat(file, (statError, stat) => {
if (statError || !stat.isFile()) {
send(res, 404, 'Not found');
return;
}
const type = TYPES[path.extname(file).toLowerCase()] || 'application/octet-stream';
res.writeHead(200, { 'Content-Type': type });
fs.createReadStream(file).pipe(res);
});
});
server.listen(PORT, () => {
console.log(`SCATMAN local site running at http://localhost:${PORT}`);
});