-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathhttp-server.js
More file actions
54 lines (42 loc) · 1.04 KB
/
http-server.js
File metadata and controls
54 lines (42 loc) · 1.04 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
var http = require('http');
var response = "<html>" +
"<head>" +
"<title>Hello World!</title>" +
"</head>" +
"<body>" +
"<h1>We made it!</h1>" +
"<p>The time is {time}!</p>" +
"<ul>" +
"<li>Node version: {node}</li>" +
"<li>V8 version: {v8}</li>" +
"<ul>" +
"</body>" +
"</html>";
var templateEngine = function (template, data) {
var vars = template.match(/\{\w+\}/g);
if (vars === null) {
return template;
}
var nonVars = template.split(/\{\w+\}/g);
var output = '';
for (var i = 0; i < nonVars.length; i++) {
output += nonVars[i];
if (i < vars.length) {
var key = vars[i].replace(/[\{\}]/g, '');
output += data[key]
}
}
return output;
};
var server = http.createServer(function (req, res) {
res.writeHead(200);
res.write(templateEngine(response, {
time: new Date().toString(),
node: process.versions.node,
v8: process.versions.v8,
}));
res.end();
});
var port = 8080;
server.listen(port);
console.log('Listening on port ' + port);