|
| 1 | +const http = require('http'); |
| 2 | +const fs = require('fs'); |
| 3 | +const countStudents = require('./3-read_file_async'); |
| 4 | + |
| 5 | +const PORT = 1245; |
| 6 | +const HOST = 'localhost'; |
| 7 | +const app = http.createServer(); |
| 8 | +const DB_PATH = process.argv.length > 2 ? process.argv[2] : ''; |
| 9 | + |
| 10 | +const SERVER_ROUTE_HANDLERS = [ |
| 11 | + { |
| 12 | + route: '/', |
| 13 | + handler(_, res) { |
| 14 | + const responseText = 'Hello Holberton School!'; |
| 15 | + res.setHeader('Content-Type', 'text/plain'); |
| 16 | + res.setHeader('Content-Length', responseText.length); |
| 17 | + res.statusCode = 200; |
| 18 | + res.write(Buffer.from(responseText)); |
| 19 | + }, |
| 20 | + }, |
| 21 | + { |
| 22 | + route: '/students', |
| 23 | + handler(_, res) { |
| 24 | + const responseParts = ['This is the list of our students']; |
| 25 | + |
| 26 | + countStudents(DB_PATH) |
| 27 | + .then((report) => { |
| 28 | + responseParts.push(report); |
| 29 | + const responseText = responseParts.join('\n'); |
| 30 | + res.setHeader('Content-Type', 'text/plain'); |
| 31 | + res.setHeader('Content-Length', responseText.length); |
| 32 | + res.statusCode = 200; |
| 33 | + res.write(Buffer.from(responseText)); |
| 34 | + }) |
| 35 | + .catch((err) => { |
| 36 | + responseParts.push(err instanceof Error ? err.message : err.toString()); |
| 37 | + const responseText = responseParts.join('\n'); |
| 38 | + res.setHeader('Content-Type', 'text/plain'); |
| 39 | + res.setHeader('Content-Length', responseText.length); |
| 40 | + res.statusCode = 200; |
| 41 | + res.write(Buffer.from(responseText)); |
| 42 | + }); |
| 43 | + }, |
| 44 | + }, |
| 45 | +]; |
| 46 | + |
| 47 | +app.on('request', (req, res) => { |
| 48 | + for (const routeHandler of SERVER_ROUTE_HANDLERS) { |
| 49 | + if (routeHandler.route === req.url) { |
| 50 | + routeHandler.handler(req, res); |
| 51 | + break; |
| 52 | + } |
| 53 | + } |
| 54 | +}); |
| 55 | + |
| 56 | +app.listen(PORT, HOST, () => { |
| 57 | + process.stdout.write(`Server listening at -> http://${HOST}:${PORT}\n`); |
| 58 | +}); |
| 59 | + |
| 60 | +module.exports = app; |
0 commit comments