-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
74 lines (60 loc) · 2.11 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
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
const fs = require('fs')
const http = require('http')
const server = http.createServer((request, response) =>{
const url = new URL(request.url, "http://${request.headers.host}")
switch(url.pathname){
case '/':
if(request.method === 'GET'){
// Extract piece of query from url.
const name = url.searchParams.get('name')
response.writeHead(200, {
'Content-Type': 'text/html'
})
// Read index as stream and save it in response.
fs.createReadStream("index.html").pipe(response)
} else if (request.method === 'POST'){
handlePostResponse(request, response)
}
break
default:
response.writeHead(404, {'Content-Type': 'text/html'})
fs.createReadStream("404.html").pipe(response)
break
}
})
server.listen(4001, ()=>{
console.log("Server listening on " + server.address().port)
})
// Function for handling POST responses
function handlePostResponse(request, response){
request.setEncoding('utf8')
// Receive chunks on 'data' event and concatenate to body variable
let body = ''
request.on('data', function (chunk) {
body += chunk
})
// When done receiving data, select a random choice for server
// Compare server choice with player's choice and send an appropriate message back
request.on('end', function () {
const choices = ['rock', 'paper', 'scissors']
const randomChoice = choices[Math.floor(Math.random() * 3)]
const choice = body
let message
const tied = `Aww, we tied! I also chose ${randomChoice}.`
const victory = `Dang it, you won! I chose ${randomChoice}.`
const defeat = `Ha! You lost. I chose ${randomChoice}.`
if (choice === randomChoice) {
message = tied
} else if (
(choice === 'rock' && randomChoice === 'paper') ||
(choice === 'paper' && randomChoice === 'scissors') ||
(choice === 'scissors' && randomChoice === 'rock')
) {
message = defeat
} else {
message = victory
}
response.writeHead(200, { 'Content-Type': 'text/plain' })
response.end(`You selected ${choice}. ${message}`)
})
}