-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
82 lines (75 loc) · 2.41 KB
/
Copy pathserver.js
File metadata and controls
82 lines (75 loc) · 2.41 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
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
const HTTP = require('http');
const { sendJSON, sendHTML } = require('./utils');
const fileSystem = require('fs');
const server = HTTP.createServer((request, response) => {
let path = request.url;
console.log("request received", path);
if (path === '/'){
response.end("home");
}
else if (path === '/opensesame'){
response.end("ooh you found the easter egg!");
}
else if (path === '/example.gif'){
let filePath = "./assets/wombat.gif";
let stat = fileSystem.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'image/gif',
'Content-length': stat.size
});
fileSystem.createReadStream(filePath).pipe(response);
}
else if (path === '/postcode.json'){
sendJSON(response, 200, [
{"name": "Melbourne", "postcode": 3000},
{"name": "Tottenham", "postcode": 3012},
{"name": "Albion", "postcode": 3020},
{"name": "Sunshine", "postcode": 3011},
]);
}
else if (path.startsWith('/postcode/')){
//get the part of the url that should be a postcode and attempt to convert it to an integer
postcodeNumber = parseInt(path.slice(10));
//check if there is a file with that number that exists in our /postcode/ folder:
pathToPostcodeFile = `./postcode/${postcodeNumber}.json`;
fileSystem.exists(pathToPostcodeFile, function(exists){
if (exists){
response.writeHead(200, {
"Content-Type": "application/json"
})
fileSystem.createReadStream(pathToPostcodeFile).pipe(response)
}
else{ //when no postcode file exists..
sendHTML(response, 404, `
<h1>Sorry I don't have anything on postcode ${postcodeNumber}</h1>
`, 'main.css');
}
})
console.log(postcodeNumber);
// sendJSON(response, 200, `./postcode/${postcodeNumber}.json`);
}
else if (path.startsWith('/assets/colors/')){
color = path.slice(15);
color = color.split('.')[0];
response.end(`
h1{
color: ${color};
}`);
}
else if (path.startsWith('/about')){ // instead of /about.html because its more modern to leave off the .html
let color = path.slice(6);
sendHTML(response, 200, `
<h1>about</h1>
<p>
This is a paragraph
</p>
`, `${color}.css`);
}
else {
sendJSON(response, 404, {"message": "page not found"});
}
});
//start the server:
server.listen(8001, (error) => {
console.log('Server has started at http://localhost:8001');
});