Skip to content

Commit 6f31f55

Browse files
committed
Add 5-http.js file
1 parent ba02f5f commit 6f31f55

File tree

2 files changed

+60
-1
lines changed

2 files changed

+60
-1
lines changed

0x05-Node_JS_basic/3-read_file_async.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ const fs = require('fs');
55
* @param {String} path - The path to the CSV data file.
66
* @returns {Promise<void>}
77
*/
8-
98
const countStudents = (path) =>
109
new Promise((resolve, reject) => {
1110
fs.readFile(path, 'utf-8', (err, data) => {

0x05-Node_JS_basic/5-http.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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

Comments
 (0)