Skip to content

Commit cccb571

Browse files
committed
Created http server with simple template parsing
1 parent d30f069 commit cccb571

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

examples/http-server.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
var http = require('http');
2+
var url = require('url');
3+
4+
var response = "<html>" +
5+
"<head>" +
6+
"<title>Hello World!</title>" +
7+
"</head>" +
8+
"<body>" +
9+
"<h1>We made it!</h1>" +
10+
"<p>The time is {time}!</p>" +
11+
"<ul>" +
12+
"<li>Node version: {node}</li>" +
13+
"<li>V8 version: {v8}</li>" +
14+
"<ul>" +
15+
"</body>" +
16+
"</html>";
17+
18+
var templateEngine = function (template, data) {
19+
20+
var vars = template.match(/\{\w+\}/g);
21+
22+
if (vars === null) {
23+
return template;
24+
}
25+
26+
var nonVars = template.split(/\{\w+\}/g);
27+
var output = '';
28+
29+
for (var i = 0; i < nonVars.length; i++) {
30+
output += nonVars[i];
31+
32+
if (i < vars.length) {
33+
var key = vars[i].replace(/[\{\}]/g, '');
34+
output += data[key]
35+
}
36+
}
37+
38+
return output;
39+
};
40+
41+
var server = http.createServer(function (req, res) {
42+
res.writeHead(200);
43+
44+
res.write(templateEngine(response, {
45+
time: new Date().toString(),
46+
node: process.versions.node,
47+
v8: process.versions.v8,
48+
}));
49+
50+
res.end();
51+
});
52+
53+
var port = 8080;
54+
server.listen(port);
55+
console.log('Listening on port ' + port);

0 commit comments

Comments
 (0)