-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
46 lines (36 loc) · 1.05 KB
/
app.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
var http = require ("http");
var fs = require('fs');
var send404Error = function(response) {
response.writeHead(404, {"Content-Type" : "text/plain"});
response.write("Page Not Found");
response.end();
}
var sendIndexFile = function(response) {
console.log("Index file has been opened");
response.writeHead(200, {"Content-Type": "text/html"});
fs.createReadStream("./index.html").pipe(response);
}
var sendRandomNumber = function(response) {
console.log("Random number has been sent");
response.writeHead(200, {"Content-Type": "application/json"});
var number = Math.floor((Math.random() * 101));
var json = JSON.stringify({
number: number
});
response.end(json);
}
var onRequest = function(request, response) {
if(request.method == "GET") {
switch (request.url) {
case "/":
sendIndexFile(response);
return;
case "/get-number":
sendRandomNumber(response);
return;
}
}
send404Error(response);
}
http.createServer(onRequest).listen(8888);
console.log("Server is now running...");