-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
executable file
·70 lines (61 loc) · 1.55 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
app.set('view engine', 'pug');
app.set("views", path.join(__dirname, "views"));
app.use(express.static('public'));
function asyncHandler(cb){
return async (req,res,next)=> {
try {
await cb(req,res,next);
} catch(err){
res.render('error', {error:err});
}
}
}
//CALL BACKS
// function getUsers(cb){
// fs.readFile('data.json', 'utf8', (err, data) => {
// if (err) return cb(err);
// const users = JSON.parse(data);
// return cb(null, users);
// });
// }
// app.get('/', (req,res) => {
// getUsers((err, users)=>{
// if(err){
// res.render('error', {error:err});
// } else {
// res.render('index', {title: "Users", users: users.users})
// }
// });
// });
// PROMISES
function getUsers(){
return new Promise((resolve, reject)=> {
fs.readFile('data.json', 'utf-8', (err, data)=> {
if(err){
reject(err);
} else {
const users = JSON.parse(data);
resolve(users);
}
});
});
}
// app.get('/', (req,res) => {
// getUsers()
// .then((users)=> {
// res.render('index', {title: "Users", users: users.users});
// })
// .catch((err)=> {
// res.render('error', {error: err});
// });
// });
// ASYNC/AWAIT
app.get('/', asyncHandler(async (req,res) => {
const users = await getUsers();
res.render('index', {title: "Users", users: users.users});
}));
app.listen(3000, () => console.log('App listening on port 3000!'));