-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
78 lines (63 loc) · 2.56 KB
/
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
var async = require('async'),
ejs = require('ejs'),
read = require('fs').readFileSync,
http = require("http"),
request = require("request"),
cheerio = require('cheerio');
var server = http.createServer(function(req, res) {
var allTitles = [];
var allPaths = [];
var main_url = req.url;
var path = main_url.substring(0, 14);
if (path === "/I/want/title/") {
var address = main_url.substring(14, main_url.length);
if (address[0] === "?") {
address = address.substring(1, address.length);
address = address.split("&");
var http_prefix = "http://";
var www_prefix = "www.";
async.forEach(address, function(addr, callback) { //async foreach used
var fetch_path = addr.substring(0, 8);
if (fetch_path === "address=") {
fetch_path = addr.substring(8, addr.length);
allPaths.push(fetch_path);
if (fetch_path.substr(0, www_prefix.length) !== www_prefix) {
fetch_path = www_prefix + fetch_path;
}
if (fetch_path.substr(0, http_prefix.length) !== http_prefix) {
fetch_path = http_prefix + fetch_path;
}
request(fetch_path, function(error, response, body) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(body);
var title = $("title").text();
allTitles.push(title);
callback();
} else if (error) {
allTitles.push("NO RESPONSE");
callback();
}
});
} else {
res.writeHead(404);
res.end('404 Not Found');
}
}, function(err) {
if (err) return next(err);
//Tell the user about the great success
res.end(ejs.render(read('views/index.ejs', 'utf-8'), {
addresses: allPaths,
allTitles: allTitles
}));
});
} else {
res.writeHead(404);
res.end(ejs.render(read('views/error.ejs', 'utf-8')));
}
} else {
res.writeHead(404);
res.end(ejs.render(read('views/error.ejs', 'utf-8')));
}
});
server.listen(3000);
console.log("Server listening on port 3000....");