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
|
#!/usr/bin/env node
// Zero-dependency static file server for local development: `node serve.js [port]`.
// ES modules don't load from file:// URLs, so the app must be served over HTTP.
// Serves build/, which is the complete deployable app (no build step; it's just the sources).
const http = require('http');
const fs = require('fs');
const path = require('path');
const root = path.join(__dirname, 'build');
const port = Number(process.argv[2] || process.env.PORT || 8080);
const types = {
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8',
'.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.ico': 'image/x-icon',
'.webp': 'image/webp', '.gif': 'image/gif',
};
http.createServer((req, res) => {
let urlPath;
try {
urlPath = decodeURIComponent(new URL(req.url, 'http://x').pathname);
} catch {
res.writeHead(400); res.end(); return; // malformed escape, e.g. "/%E0"
}
let file = path.normalize(path.join(root, urlPath));
// `root + sep` so a sibling such as "/work-other" doesn't pass for "/work"
if (file !== root && !file.startsWith(root + path.sep)) { res.writeHead(403); res.end(); return; }
if (fs.existsSync(file) && fs.statSync(file).isDirectory()) file = path.join(file, 'index.html');
fs.readFile(file, (err, data) => {
if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Not found'); return; }
res.writeHead(200, { 'Content-Type': types[path.extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-cache' });
res.end(data);
});
}).listen(port, () => console.log(`Atelier running at http://localhost:${port}/`));
|