-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (40 loc) · 1.67 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
const fs = require('fs');// to read form json file
const http = require('http')//to create server
const url = require('url')// to get the pathname like '/','/overview' etc.
const replaceTemplate =require('../modules/replaceTemplate.js')//used to replace each json object with card html code
const tempCard = fs.readFileSync('../templates/template-card.html','utf-8')
const tempOverview = fs.readFileSync('../templates/template-overview.html','utf-8')
const tempProduct = fs.readFileSync('../templates/template-product.html','utf-8')
const data = fs.readFileSync('../dev-data/data.json','utf-8')
const dataObj = JSON.parse(data)//converts the data in JSON format
const server = http.createServer((req,res)=>
{
const {query,pathname} = url.parse(req.url)
const sm = url.parse(req.url)
if(pathname === '/overview' || pathname === '/')
{
res.writeHead(200,{
'Content-type':'text/html'//converts the raw html to static website
})
const cardsHTML = dataObj.map(el=>replaceTemplate(tempCard,el)).join('')
const output = tempOverview.replace('{%PRODUCT_CARDS}',cardsHTML)//replaces the place holder {%PRODUCT_CARDS} with HTML code
res.end(output)
}
else if (pathname === '/product')
{
const product = dataObj[query[3]]
const output = replaceTemplate(tempProduct,product)
res.end(output)
}
else
{
res.writeHead(404,
{
'Content-type':'text/html'
});
res.end('<h1>Page Not Found</h1>')
}
})
server.listen(8000,'127.0.0.1',()=>{
console.log('Listening from port 8000')
})