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 48 49
| const http = require('http'); const url = require("url"); const fs = require("fs");
const server = http.createServer((req, res) => { const reqPath = url.parse(req.url).path.split('?')[0]; const filepath = __dirname + '/files' + reqPath;
const resHeader = { 'Content-Type': 'text/html;charset=utf8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': true, 'Access-Control-Allow-Headers': 'x-requested-with, content-type', }
fs.exists(filepath, function (exists) { if (exists) { fs.stat(filepath, function (err, stats) { if (err) { res.writeHead(500, resHeader); res.end('<div styel="color:black;font-size:22px;">server error</div>'); } else { if (stats.isFile()) { const file = fs.createReadStream(filepath); res.writeHead(200, resHeader); file.pipe(res); } else { fs.readdir(filepath, function (err, files) { let str = '<ul>'; for (let i in files) { str += `<li><a href="${reqPath.replace(/\/$/, '')}/${files[i]}">${files[i]}</a></li>` } str += '</ul>' res.writeHead(200, resHeader); res.write(str); }); } } }); } else { res.writeHead(404, { 'Content-Type': 'text/html;charset=utf8' }); res.end('<div styel="color:black;font-size:22px;">404 not found</div>'); } }); }); server.listen(3000);
|