-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
71 lines (56 loc) · 2.5 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
const fs = require('fs');
const http = require('http');
const url = require('url');
const json = fs.readFileSync(`${__dirname}/data/data.json`, 'utf-8');
const laptopData = JSON.parse(json);
const server = http.createServer((req, res) => {
const pathName = url.parse(req.url, true).pathname;
const id = url.parse(req.url, true).query.id;
// console.log(url.parse(req.url, true));
console.log(id);
// PRODUCTS OVERVIEW
if (pathName === '/products' || pathName === '/') {
res.writeHead(200, {'Content-type': 'text/html'});
fs.readFile(`${__dirname}/templates/template-overview.html`, 'utf-8', (err, data) => {
let overviewOutput = data;
fs.readFile(`${__dirname}/templates/template-card.html`, 'utf-8', (err, data) => {
const cardsOutput = laptopData.map(el => replaceTemplate(data, el)).join('');
overviewOutput = overviewOutput.replace('{%CARDS%}', cardsOutput);
res.end(overviewOutput);
});
});
// LAPTOP DETAIL
} else if (pathName === '/laptop' && id < laptopData.length){
res.writeHead(200, {'Content-type': 'text/html'});
fs.readFile(`${__dirname}/templates/template-laptop.html`, 'utf-8', (err, data) => {
const laptop = laptopData[id];
const output = replaceTemplate(data, laptop);
res.end(output);
});
// IMAGES
} else if ((/\.(jpg|jpeg|png|gif)$/i).test(pathName)) {
fs.readFile(`${__dirname}/data/img${pathName}`, (err, data) => {
res.writeHead(200, {'Content-type': 'image/jpg'});
res.end(data);
});
// URL NOT FOUND
} else {
res.writeHead(404, {'Content-type': 'text/html'});
res.end('URL was not found on the server!');
}
});
server.listen(1337, '127.0.0.1', () => {
console.log('Listening for requests now');
});
function replaceTemplate(originalHTML, laptop) {
let output = originalHTML.replace(/{%PRODUCTNAME%}/g, laptop.productName);
output = output.replace(/{%IMAGE%}/g, laptop.image);
output = output.replace(/{%PRICE%}/g, laptop.price);
output = output.replace(/{%SCREEN%}/g, laptop.screen);
output = output.replace(/{%CPU%}/g, laptop.cpu);
output = output.replace(/{%STORAGE%}/g, laptop.storage);
output = output.replace(/{%RAM%}/g, laptop.ram);
output = output.replace(/{%DESCRIPTION%}/g, laptop.description);
output = output.replace(/{%ID%}/g, laptop.id);
return output;
}