-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserve.js
More file actions
53 lines (44 loc) · 1.5 KB
/
Copy pathserve.js
File metadata and controls
53 lines (44 loc) · 1.5 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 3000;
const PUBLIC_DIR = path.join(__dirname, 'web');
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.mjs': 'application/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.woff2': 'font/woff2',
'.woff': 'font/woff'
};
const server = http.createServer((req, res) => {
let reqPath = req.url.split('?')[0];
if (reqPath === '/' || reqPath === '') reqPath = '/index.html';
const safePath = path.normalize(reqPath).replace(/^(\.\.[\/\\])+/, '');
const filePath = path.join(PUBLIC_DIR, safePath);
fs.stat(filePath, (err, stats) => {
if (err || !stats.isFile()) {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('404 Not Found');
return;
}
const ext = path.extname(filePath).toLowerCase();
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
res.writeHead(200, {
'Content-Type': contentType,
'Cache-Control': 'no-cache',
'Access-Control-Allow-Origin': '*'
});
const stream = fs.createReadStream(filePath);
stream.pipe(res);
});
});
server.listen(PORT, '0.0.0.0', () => {
console.log(`[Pen 11] Local Live Server running at http://localhost:${PORT}`);
});