-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
50 lines (32 loc) · 1.27 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const fs = require('fs');
const path = require('path');
const express = require("express");
const app = express();
app.use(express.urlencoded({extended: false}));
app.get("/currenttime", function (request, response) {
response.send("<h1>" + new Date().toISOString() + "</h1>");
});
app.get("/", function (req, res) {
res.send('<form action="/store-user" method="POST"><label>Your name .</label><br><input type="text" name="username"></input><br><button>Submit</button></form>');
});
app.post('/store-user', function(req, res){
const userName = req.body.username;
const filePath = path.join(__dirname, 'data', 'users.json');
const fileData = fs.readFileSync(filePath);
const existingUsers = JSON.parse(fileData);
existingUsers.push(userName);
fs.writeFileSync(filePath, JSON.stringify(existingUsers));
res.send('<h2>Username Stored</h2>');
});
app.get('/users', function(req, res){
const filePath = path.join(__dirname, 'data', 'users.json');
const fileData = fs.readFileSync(filePath);
const existingUsers = JSON.parse(fileData);
let responseData = '<ul>';
for(const user of existingUsers){
responseData = responseData += '<li>' + user + '</li>'
}
responseData += '<ul>';
res.send(responseData);
})
app.listen(3000);