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
| const fs = require('fs'); const path = require('path');
const mime = require('mime');
function render(res, path, type = '') { res.writeHead(200, { 'Content-Type': `${type ? type : 'text/html'};charset=utf8` }); res.write(fs.readFileSync(path), 'utf-8'); res.end(); }
const route = { '/login'(req, res) { render(res, './static/login.html'); }, '/home'(req, res) { render(res, './static/home.html'); }, '/404'(req, res) { const url = new URL(req.url, 'http://127.0.0.1');
let pathname = path.join(__dirname, 'static', url.pathname); if (readStaticFile(res, pathname)) { return; } res.writeHead(404, { 'Content-Type': 'text/html;charset=utf8' }); res.write(fs.readFileSync('./static/404.html'), 'utf-8'); res.end(); }, };
function readStaticFile(res, pathname) { let houzhui = pathname.split('.'); if (fs.existsSync(pathname)) { render(res, pathname, mime.getType(houzhui[houzhui.length - 1])); return true; } else { return false; } }
module.exports = route;
|