-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpJsonServer.js
More file actions
71 lines (48 loc) · 1.72 KB
/
httpJsonServer.js
File metadata and controls
71 lines (48 loc) · 1.72 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
var http = require('http');
var url = require('url');
var server = http.createServer(function(request, response) {
if (request.method === 'GET') {
var parsedURL = url.parse(request.url, true); // this is the URL object with properties (like example in direcitons)
var date = new Date(parsedURL.query['iso']);
response.writeHead(200, {"Content-Type": "application/json"});
if (parsedURL.pathname === "/api/parsetime") {
response.end(JSON.stringify({hour: + date.getHours(),
minute: + date.getMinutes(),
second: + date.getSeconds() }));
}
else if (parsedURL.pathname === "/api/unixtime") {
response.end(JSON.stringify({unixtime: date.valueOf()}));
}
}
});
server.listen(process.argv[2]);
// Alternate way (solution)
// var http = require('http')
// var url = require('url')
// function parsetime (time) {
// return {
// hour: time.getHours(),
// minute: time.getMinutes(),
// second: time.getSeconds()
// }
// }
// function unixtime (time) {
// return { unixtime : time.getTime() }
// }
// var server = http.createServer(function (req, res) {
// var parsedUrl = url.parse(req.url, true)
// var time = new Date(parsedUrl.query.iso)
// var result
// if (/^\/api\/parsetime/.test(req.url))
// result = parsetime(time)
// else if (/^\/api\/unixtime/.test(req.url))
// result = unixtime(time)
// if (result) {
// res.writeHead(200, { 'Content-Type': 'application/json' })
// res.end(JSON.stringify(result))
// } else {
// res.writeHead(404)
// res.end()
// }
// })
// server.listen(Number(process.argv[2]))