|
| 1 | +const http = require('http'); |
| 2 | +const url = require('url'); |
| 3 | +const fs = require('fs'); |
| 4 | +const path = require('path'); |
| 5 | +const port = 9000; |
| 6 | + |
| 7 | +// maps file extention to MIME types |
| 8 | +// full list can be found here: https://www.freeformatter.com/mime-types-list.html |
| 9 | +const mimeType = { |
| 10 | + '.ico': 'image/x-icon', |
| 11 | + '.html': 'text/html', |
| 12 | + '.js': 'text/javascript', |
| 13 | + '.json': 'application/json', |
| 14 | + '.css': 'text/css', |
| 15 | + '.png': 'image/png', |
| 16 | + '.jpg': 'image/jpeg', |
| 17 | + '.wav': 'audio/wav', |
| 18 | + '.mp3': 'audio/mpeg', |
| 19 | + '.svg': 'image/svg+xml', |
| 20 | + '.pdf': 'application/pdf', |
| 21 | + '.zip': 'application/zip', |
| 22 | + '.doc': 'application/msword', |
| 23 | + '.eot': 'application/vnd.ms-fontobject', |
| 24 | + '.ttf': 'application/x-font-ttf', |
| 25 | +}; |
| 26 | + |
| 27 | +http |
| 28 | + .createServer(function (req, res) { |
| 29 | + console.log(`${req.method} ${req.url}`); |
| 30 | + |
| 31 | + // parse URL |
| 32 | + const parsedUrl = url.parse(req.url); |
| 33 | + const sanitizePath = path |
| 34 | + .normalize(parsedUrl.pathname) |
| 35 | + .replace(/^(\.\.[\/\\])+/, ''); |
| 36 | + let pathname = path.join(__dirname, sanitizePath); |
| 37 | + |
| 38 | + fs.exists(pathname, function (exist) { |
| 39 | + if (!exist) { |
| 40 | + // if the file is not found, return 404 |
| 41 | + res.statusCode = 404; |
| 42 | + res.end(`File ${pathname} not found!`); |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + // if is a directory return the list of files |
| 47 | + if (fs.statSync(pathname).isDirectory()) { |
| 48 | + fs.readdir(pathname, function (err, files) { |
| 49 | + //handling error |
| 50 | + if (err) { |
| 51 | + return console.log('Unable to scan directory: ' + err); |
| 52 | + } |
| 53 | + |
| 54 | + res.setHeader('Content-type', mimeType['.json']) |
| 55 | + res.end(JSON.stringify(files)); |
| 56 | + }); |
| 57 | + } |
| 58 | + |
| 59 | + // read file from file system |
| 60 | + fs.readFile(pathname, function (err, data) { |
| 61 | + if (err) { |
| 62 | + res.statusCode = 500; |
| 63 | + res.end(`Error getting the file: ${err}.`); |
| 64 | + } else { |
| 65 | + // based on the URL path, extract the file extention. e.g. .js, .doc, ... |
| 66 | + const ext = path.parse(pathname).ext; |
| 67 | + // if the file is found, set Content-type and send data |
| 68 | + res.setHeader('Content-type', mimeType[ext] || 'text/plain'); |
| 69 | + res.end(data); |
| 70 | + } |
| 71 | + }); |
| 72 | + }); |
| 73 | + }) |
| 74 | + .listen(parseInt(port)); |
| 75 | + |
| 76 | +console.log(`Server listening on port ${port}`); |
0 commit comments