service/test/router.js
1 const http = require('http'); 2 const fs = require('fs'); 3 4 const start = function (req, resp) { 5 console.log('t', new Date().getTime()); 6 console.log('url', req.url); 7 router(req, resp); 8 }; 9 const routers = { 10 paths: [ 11 ['path', function (req, resp) { 12 resp.write('您访问到了path应用lll') 13 }], 14 ['/aa', function (req, resp) { 15 resp.write('您访问到了' + req.url + '应用') 16 }] 17 ] 18 }; 19 const stat = { 20 match: 200, 21 noMatch: 404, 22 error: { 23 router: 500 24 } 25 }; 26 const home = ['index', 'index.html', 'index.htm']; 27 const match = function (uu, ps) { 28 let paths = ps || routers.paths; 29 for (let i = 0; i < paths.length; i++) { 30 if (paths[i].length > 1) { 31 if (mate(uu, paths[i][0])) return paths[i][1]; 32 } 33 } 34 }; 35 const mate = function (u, r) { 36 return (new RegExp('^' + r.replace(/\*/igm, '.*') + '$')).test(u); 37 }; 38 const router = function (req, resp) { 39 const ps = routers.paths; 40 let url = req.url; 41 if (url.indexOf('?') > -1) url = url.split('?')[0]; 42 if (url.indexOf(';') > -1) url = url.split(';')[0]; 43 const m = match(url, ps); 44 resp.setHeader('Content-Type', 'text/html;charset=utf-8'); 45 if (typeof m === 'function') { 46 m(req, resp); 47 resp.end(); 48 } else { 49 //No router 50 let fileP = '../web/' + url; 51 fs.exists(fileP, (e) => { 52 if (!e || !fs.statSync(fileP).isFile()) { 53 let us = url.split('/'); 54 if (us[us.length - 1].indexOf('.') > -1) { 55 back404(resp); 56 } else { 57 let isNoSuchFile = true; 58 let file = ''; 59 for (let i = 0; i < home.length; i++) { 60 let filePT = fileP + home[i]; 61 fs.exists(filePT, function (e) { 62 if (e) { 63 isNoSuchFile = false; 64 file = filePT; 65 } 66 if (i === home.length - 1) { 67 if (isNoSuchFile) { 68 back404(resp); 69 } else { 70 backFile(file, resp); 71 } 72 } 73 }); 74 if (!isNoSuchFile) break; 75 } 76 } 77 } else { 78 backFile(fileP, resp); 79 } 80 }) 81 } 82 83 const backFile = function (file, resp) { 84 resp.write(fs.readFileSync(file)); 85 resp.end(); 86 }; 87 const back404 = function (resp) { 88 resp.statusCode = stat.noMatch; 89 resp.write('No such file.'); 90 resp.end(); 91 } 92 }; 93 94 http.createServer(start).listen(9999); 95 console.log('Service start OK! http://localhost:9999');
service/web/index.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>index</title> 6 </head> 7 <body> 8 <h3>我访问到index了</h3> 9 </body> 10 </html>