-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatic-server.js
104 lines (101 loc) · 3.43 KB
/
static-server.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
var fs = require('fs');
var http = require('http');
var url = require('url');
var ROOT_DIR = "./root";
var server = http.createServer(function (req, res) {
var urlObj = url.parse(req.url, true, false);
fs.readFile(ROOT_DIR + urlObj.pathname, function (err,data) {
if(urlObj.pathname.indexOf("getcity") != -1) {
// Execute the REST service
console.log("In REST Service.");
fs.readFile(ROOT_DIR + '/cities.dat.txt', function(err, data) {
if(err) {throw err;}
console.log(urlObj.query);
var regEx = new RegExp("^" + urlObj.query["q"]);
console.log(regEx);
cities = data.toString().split("\n");
var result = [];
cities.forEach(function(elem) {
if(elem.search(regEx) != -1) {
console.log(elem);
result.push({city:elem});
}
});
console.log(JSON.stringify(result));
res.writeHead(200);
res.end(JSON.stringify(result));
});
}
else if (urlObj.pathname === "/comment") {
console.log("comment route");
if(req.method === "POST") {
console.log("POST comment route");
var jsonData = "";
req.on('data', function (chunk) {
jsonData += chunk;
});
req.on('end', function () {
var reqObj = JSON.parse(jsonData);
console.log(reqObj);
console.log("Name: "+reqObj.Name);
console.log("Comment: "+reqObj.Comment);
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost/comments", function(err,db) {
if(err) {throw err;}
db.collection("comments").insert(reqObj,function(err, records) {
console.log("Record added as " + records[0]._id);
});
});
});
res.writeHead(204);
res.end();
}
else if(req.method === "GET") {
console.log("GET comment Route");
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost/comments", function(err,db) {
if(err) {throw err;}
db.collection("comments",function(err,comments) {
comments.find(function(err, items) {
items.toArray(function(err,itemArray){
console.log("Document Array: ");
console.log(itemArray);
res.writeHead(200);
res.end(JSON.stringify(itemArray));
});
});
});
});
}
}
else {
// Serve static files
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.writeHead(200);
res.end(data);
}
});
});
server.listen(80);
exports.server = server;
/*var options = {
hostname: 'localhost',
port: '80',
path: '/hello.html'
};
function handleResponse(response) {
var serverData = '';
response.on('data', function (chunk) {
serverData += chunk;
});
response.on('end', function () {
console.log(serverData);
});
}
http.request(options, function(response){
handleResponse(response);
}).end();*/