Skip to content

Commit daa0ff8

Browse files
committed
Add 7-http_express.js file
1 parent 913f735 commit daa0ff8

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

0x05-Node_JS_basic/7-http_express.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
const express = require('express');
2+
const countStudents = require('./3-read_file_async');
3+
const app = express();
4+
5+
const PORT = 1245;
6+
const DB_PATH = process.argv.length > 2 ? process.argv[2] : '';
7+
8+
app.get('/', (_, res) => {
9+
res.send('Hello Holberton School!');
10+
});
11+
12+
app.get('/students', (_, res) => {
13+
const responseParts = ['This is the list of our students'];
14+
15+
countStudents(DB_PATH)
16+
.then((report) => {
17+
responseParts.push(report);
18+
const responseText = responseParts.join('\n');
19+
res.setHeader('Content-Type', 'text/plain');
20+
res.setHeader('Content-Length', responseText.length);
21+
res.statusCode = 200;
22+
res.write(Buffer.from(responseText));
23+
})
24+
.catch((err) => {
25+
responseParts.push(err instanceof Error ? err.message : err.toString());
26+
const responseText = responseParts.join('\n');
27+
res.setHeader('Content-Type', 'text/plain');
28+
res.setHeader('Content-Length', responseText.length);
29+
res.statusCode = 200;
30+
res.write(Buffer.from(responseText));
31+
});
32+
});
33+
34+
app.listen(PORT, () => {
35+
console.log(`Server listening on PORT ${PORT}`);
36+
});
37+
38+
module.exports = app;

0 commit comments

Comments
 (0)