-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnodejsserver.js
More file actions
122 lines (86 loc) · 3.08 KB
/
nodejsserver.js
File metadata and controls
122 lines (86 loc) · 3.08 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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
const http = require("http")
const url = require('url')
const hostname = '127.0.0.1'
const port = process.env.PORT || 8080
function ConstructPage(addrParams, res){
body = "<html>"
body += "<head></head>"
body += "<body>"
body += "<h1> Following are the titles of given websites: </h1>"
body += "<ul>"
res.write(body);
addrParams.forEach((elem, ind, arr) => {
webUrl = "http://" + elem;
//console.log(webUrl)
data = "";
webTitle = "";
req = http.request(webUrl, (resp) => {
//console.log(webUrl)
resp.on('data', (chunk) => {
data += chunk
}).on('end', () => {
webTitle = data.match("<title>(.*?)</title>");
if(webTitle != null)
webTitle = webTitle[1]
//console.log(webTitle)
console.log(webUrl)
//console.log(elem)
listTag = "<li>" + webUrl + " - " + webTitle + "</li>";
res.write(listTag)
console.log(arr)
if(ind == arr.length-1){
body = "</ul>";
body += "</body>";
body += "</html>";
res.write(body)
res.end()
}
})
})
req.on('error', () => {
webTitle = "NO RESPONSE"
//console.log(webTitle)
console.log(webUrl)
//console.log(elem)
listTag = "<li>" + webUrl + " - NO RESPONSE</li>";
res.write(listTag)
//console.log(arr)
if(ind == arr.length-1){
body = "</ul>";
body += "</body>";
body += "</html>";
res.write(body)
res.end()
}
})
req.end();
});
}
const server = http.createServer((req, res) => {
addr = new URL(req.url, `http:\\${req.headers.host}`)
if(addr.pathname == "/I/want/title/"){
res.statusCode = 200
res.setHeader('Content-Type', 'text/html')
addrParams = addr.searchParams.getAll("address")
if(addrParams.length >= 1){
ConstructPage(addrParams, res)
}
else{
res.statusCode = 404
res.setHeader('Content-Type', 'text/plain')
res.write("Error 404")
res.end();
}
}
else if(addr.pathname != "/favicon.ico"){
res.statusCode = 404
res.setHeader('Content-Type', 'text/plain')
res.write("Error 404")
res.end();
}
else { // if it is favion.ico request, then simply ignore
}
})
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})