forked from xkiver/nodejs_simple_server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_example.js
82 lines (75 loc) · 2.68 KB
/
node_example.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
75
76
77
78
79
80
81
82
var http = require('http')
var server = http.createServer(function (request, response) {
var url = request.url
var data = url.split('?')
if(data[0] === '/suma') {
var suma = 0
var input = data[1].split('&')
input.forEach(function(numero) {
var splitted = numero.split('=')[1]
if(isNumeric(splitted)) {
//Ok, it's a number
var number = Number(splitted)
suma += number
} else {
//It's not a number, so we show an error message and sends to the client
response.writeHead(400, {'Content-Type': 'application/json'})
response.end(JSON.stringify({result:'error, el input debe ser numerico'}))
}
})
//If everithing was OK, we send code 200 response, using json format
response.writeHead(200, {'Content-Type': 'application/json'})
response.end(JSON.stringify({result:suma}))
}
if(data[0] === '/multiplicacion') {
var mult = 1
var input = data[1].split('&')
input.forEach(function(numero) {
var splitted = numero.split('=')[1]
if(isNumeric(splitted)) {
//Ok, it's a number
var number = Number(splitted)
mult = mult*number
} else {
//It's not a number, so we show an error message and sends to the client
response.writeHead(400, {'Content-Type': 'application/json'})
response.end(JSON.stringify({result:'error, el input debe ser numerico'}))
}
})
//If everithing was OK, we send code 200 response, using json format
response.writeHead(200, {'Content-Type': 'application/json'})
response.end(JSON.stringify({result:mult}))
}
if(data[0] === '/fibonacci') {
var input = data[1].split('=')[1]
if(isNumeric(input)) {
//Ok, it's a number
fib = fibonacci(input)
} else {
//It's not a number, so we show an error message and sends to the client
response.writeHead(400, {'Content-Type': 'application/json'})
response.end(JSON.stringify({result:'error, el input debe ser numerico'}))
}
//If everithing was OK, we send code 200 response, using json format
response.writeHead(200, {'Content-Type': 'application/json'})
response.end(JSON.stringify({result:fib}))
}
})
/**
** isNumeric returns true if input is a number. This can be done using the oppsite behaviour from isNaN function
**/
function isNumeric(num) {
//isNaN returns false if the input is a number, true otherwise
return !isNaN(num)
}
/**
** fibonacci returns true if input is a number. This can be done using the oppsite behaviour from isNaN function
**/
function fibonacci(n){
let arr = [0, 1];
for (let i = 2; i < n + 1; i++){
arr.push(arr[i - 2] + arr[i -1])
}
return arr[n]
}
server.listen(8080)