22 lines
1.0 KiB
JavaScript
22 lines
1.0 KiB
JavaScript
const http = require('http');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const PORT = 3000;
|
|
const ROOT = __dirname;
|
|
const MIME = {
|
|
'.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8',
|
|
'.js': 'application/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8',
|
|
'.md': 'text/plain; charset=utf-8', '.png': 'image/png', '.jpg': 'image/jpeg',
|
|
'.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon',
|
|
};
|
|
http.createServer((req, res) => {
|
|
let fp = path.join(ROOT, decodeURIComponent(req.url.split('?')[0]));
|
|
if (fs.existsSync(fp) && fs.statSync(fp).isDirectory()) fp = path.join(fp, 'index.html');
|
|
const ext = path.extname(fp).toLowerCase();
|
|
fs.readFile(fp, (err, data) => {
|
|
if (err) { res.writeHead(404); res.end('404: ' + req.url); return; }
|
|
res.writeHead(200, { 'Content-Type': MIME[ext] || 'application/octet-stream' });
|
|
res.end(data);
|
|
});
|
|
}).listen(PORT, () => console.log('Server: http://localhost:' + PORT));
|