|
| 1 | +const fs = require('fs'); |
| 2 | +const http = require('http'); |
| 3 | +const mime = require('mime'); |
| 4 | +const path = require('path'); |
| 5 | +const url = require('url'); |
| 6 | + |
| 7 | +function walkDirectory(dirPath, callback) { |
| 8 | + const dirents = fs.readdirSync(dirPath, { withFileTypes: true }); |
| 9 | + |
| 10 | + dirents.forEach(dirent => { |
| 11 | + if (dirent.isDirectory()) { |
| 12 | + walkDirectory(path.join(dirPath, dirent.name), callback); |
| 13 | + } else { |
| 14 | + callback(path.join(dirPath, dirent.name)); |
| 15 | + } |
| 16 | + }); |
| 17 | +} |
| 18 | + |
| 19 | +const rootDirectory = path.resolve(process.argv[2] || './'); |
| 20 | + |
| 21 | +const files = new Set(); |
| 22 | +walkDirectory(rootDirectory, (file) => { |
| 23 | + file = file.substr(rootDirectory.length); |
| 24 | + files.add(file); |
| 25 | +}); |
| 26 | +console.log(`Found ${files.size} in '${rootDirectory}'...`); |
| 27 | + |
| 28 | +const server = http.createServer(); |
| 29 | +server.on('request', (request, response) => { |
| 30 | + const requestUrl = url.parse(request.url); |
| 31 | + const requestedPath = requestUrl.pathname; |
| 32 | + |
| 33 | + if (!files.has(requestedPath)) { |
| 34 | + console.log('404 %s', requestUrl.href); |
| 35 | + response.writeHead(404); |
| 36 | + response.end(); |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + const contentType = mime.getType(path.extname(requestedPath)); |
| 41 | + |
| 42 | + console.log('200 %s', requestUrl.href); |
| 43 | + response.writeHead(200, { 'Content-type': contentType }); |
| 44 | + fs.createReadStream(path.join(rootDirectory, requestedPath)) |
| 45 | + .pipe(response); |
| 46 | +}); |
| 47 | + |
| 48 | +const port = 3000; |
| 49 | +console.log('Starting server on port %d.', port); |
| 50 | +console.log('Go to: http://localhost:%d', port); |
| 51 | +server.listen(port); |
0 commit comments