-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (65 loc) · 2.69 KB
/
index.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const fs = require('fs');
const http = require('http');
const url = require('url');
const slugify = require('slugify');
const replaceTemplate = require('./Modules/replacetemplate')
//////////////////////////////////
// Files
// Blocking synchronous way
// const textIn = fs.readFileSync('./txt/input.txt', 'utf-8');
// console.log(textIn);
// const textOut = `This is what we know about the Avocado: ${textIn}.\nCreated on ${Date.now()}`;
// fs.writeFileSync('./txt/output.txt', textOut);
// console.log('File written!');
// Non-blocking, Asynchronous way
// fs.readFile('./txt/start.txt', 'utf-8', (err, data1) => {
// fs.readFile(`./txt/${data1}.txt`, 'utf-8', (err, data2) => {
// console.log(data2);
// fs.readFile(`./txt/append.txt`, 'utf-8', (err, data3) => {
// console.log(data3);
// fs.writeFile('./txt/final.txt', `${data2}\n${data3}`, 'utf-8', err => {
// console.log('Your file has been written');
// })
// });
// });
// });
// console.log('will read file!');
////////////////////////////////////////
// Server
const tempOverview = fs.readFileSync(`${__dirname}/templates/template-overview.html`, 'utf-8');
const tempCard = fs.readFileSync(`${__dirname}/templates/template-card.html`, 'utf-8');
const tempProduct = fs.readFileSync(`${__dirname}/templates/template-product.html`, 'utf-8');
const data = fs.readFileSync(`${__dirname}/dev-data/data.json`, 'utf-8');
const dataObj = JSON.parse(data);
const slugs = dataObj.map(el => slugify(el.productName, { lower: true}));
console.log(slugs);
const server = http.createServer((req, res) => {
const { query, pathname } = url.parse(req.url, true);
// Overview Page
if (pathname === '/' || pathname === '/overview') {
res.writeHead(200, { 'Content-type': 'text/html'});
const cardsHtml = dataObj.map(el => replaceTemplate(tempCard, el)).join('');
const output = tempOverview.replace('{%PRODUCT_CARDS%}', cardsHtml);
res.end(output);
// Product Page
} else if (pathname === '/product') {
res.writeHead(200, { 'Content-type': 'text/html'});
const product = dataObj[query.id];
const output = replaceTemplate(tempProduct, product);
res.end(output);
// API
} else if (pathname === '/api') {
res.writeHead(200, {'Content-type': 'application/json'});
res.end(data);
// Not found
} else {
res.writeHead(404, {
'Content-type': 'text/html',
'my-own-header': 'hello-world'
});
res.end('<h1>Page not found!</h1>');
}
});
server.listen(8000, '127.0.0.1', () => {
console.log('Listening to requests on port 8000');
});