62 lines
1.6 KiB
JavaScript
62 lines
1.6 KiB
JavaScript
const http = require('http');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
const root = __dirname;
|
|
const port = process.argv[2] ? parseInt(process.argv[2], 10) : 8181;
|
|
|
|
const mime = {
|
|
'.html': 'text/html; charset=utf-8',
|
|
'.js': 'text/javascript; charset=utf-8',
|
|
'.css': 'text/css; charset=utf-8',
|
|
'.json': 'application/json; charset=utf-8',
|
|
'.png': 'image/png',
|
|
'.jpg': 'image/jpeg',
|
|
'.jpeg': 'image/jpeg',
|
|
'.gif': 'image/gif',
|
|
'.svg': 'image/svg+xml',
|
|
'.webp': 'image/webp',
|
|
'.mp4': 'video/mp4',
|
|
'.woff': 'font/woff',
|
|
'.woff2': 'font/woff2',
|
|
'.ttf': 'font/ttf',
|
|
'.ico': 'image/x-icon',
|
|
};
|
|
|
|
const server = http.createServer((req, res) => {
|
|
let reqPath = decodeURIComponent(req.url.split('?')[0]);
|
|
if (reqPath === '/') reqPath = '/index.html';
|
|
let filePath = path.join(root, reqPath);
|
|
|
|
if (!filePath.startsWith(root)) {
|
|
res.writeHead(403);
|
|
res.end('Forbidden');
|
|
return;
|
|
}
|
|
|
|
fs.stat(filePath, (err, stats) => {
|
|
if (err) {
|
|
res.writeHead(404);
|
|
res.end('Not found: ' + reqPath);
|
|
return;
|
|
}
|
|
if (stats.isDirectory()) {
|
|
filePath = path.join(filePath, 'index.html');
|
|
}
|
|
fs.readFile(filePath, (err2, data) => {
|
|
if (err2) {
|
|
res.writeHead(404);
|
|
res.end('Not found: ' + reqPath);
|
|
return;
|
|
}
|
|
const ext = path.extname(filePath).toLowerCase();
|
|
res.writeHead(200, { 'Content-Type': mime[ext] || 'application/octet-stream' });
|
|
res.end(data);
|
|
});
|
|
});
|
|
});
|
|
|
|
server.listen(port, () => {
|
|
console.log(`Static server running at http://localhost:${port}/`);
|
|
});
|