-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_server.js
More file actions
38 lines (31 loc) · 1.11 KB
/
node_server.js
File metadata and controls
38 lines (31 loc) · 1.11 KB
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
const http = require('http');
const port = process.env.PORT || 8000; //
const fs = require('fs');
const serveStaticFile = (res, path, contentType, responseCode=200)=>{
fs.readFile(__dirname + path, (err, data) => {
if(err){
res.writeHead(500, {'contentType': 'text/plain'})
res.end(`500 - Server error: ${err.message}`)
}
res.writeHead(responseCode, {'contentType': contentType})
res.end(data)
})
}
const server = http.createServer((req, res) => {
const path = req.url.replace(/\/$/, '').toLowerCase()
switch(path){
case '':
serveStaticFile(res, '/public/index.html', 'text/html')
break;
case '/about':
serveStaticFile(res, '/public/about.html', 'text/html')
break;
case '/contact':
serveStaticFile(res, '/public/contact.html', 'text/html')
break;
default:
serveStaticFile(res, '/public/404.html', 'text/html')
break;
}
})
server.listen(port, ()=> console.log(`The server is running at the port ${port} to exit click ctrl C`))