-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.js
117 lines (104 loc) · 2.82 KB
/
demo.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
105
106
107
108
109
110
111
112
113
114
115
116
117
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
var querystring = require('querystring');
var framework = function (req, res) {
var index = -1;
var next = function () {
index++;
var middleware = framework.stack[index];
middleware.handle(req, res, next);
};
next();
};
framework.stack = [];
framework.use = function (route, handle) {
console.log('hahah');
if (typeof route === 'function') {
handle = route;
route = '/';
}
framework.stack.push({route: route, handle: handle});
};
var server = function () {
return framework;
};
server.staticFile = function (root) {
return function (req, res, next) {
var pathname = url.parse(req.url).pathname;
fs.readFile(path.join(root, pathname), function (err, file) {
if (err) {
if (err.code === 'ENOENT') {
return next();
} else {
return next(err);
}
}
res.end(file);
});
};
};
server.render = function (viewpath) {
var cache = {};
var complie = function (str) {
var tpl = str.replace(/\n/g, '\\n')
.replace(/<%=([\s\S]+?)%>/g, function (match, code) {
// 转义
return "' + escape(" + code + ") + '";
}).replace(/<%=([\s\S]+?)%>/g, function (match, code) {
// 正常输出
return "' + " + code + "+ '";
}).replace(/<%([\s\S]+?)%>/g, function (match, code) {
// 可执行代码
return "';\n" + code + "\ntpl += '";
}).replace(/\'\n/g, '\'')
.replace(/\n\'/gm, '\'');
tpl = "tpl = '" + tpl + "';";
// 转换空行
tpl = tpl.replace(/''/g, '\'\\n\'');
tpl = 'var tpl = "";\nwith (obj || {}) {\n' + tpl + '\n}\nreturn tpl;';
console.log(tpl);
return new Function('obj', 'escape', tpl);
};
http.ServerResponse.prototype.render = function (viewname, data) {
var res = this;
if (!cache[viewname]) {
var text;
try {
text = fs.readFileSync(path.join(viewpath, viewname), 'utf8');
} catch (ex) {
res.writeHead(500, {'Content-Type': 'text/html'});
res.end('模版文件错误');
return;
}
cache[viewname] = complie(text);
}
var complied = cache[viewname];
res.writeHead(200, {'Content-Type': 'text/html'});
var html = complied(data);
res.end(html);
};
return function (req, res, next) {
next();
};
};
var app = server();
app.use(server.staticFile(path.join(__dirname, 'assets')));
app.use(server.render(path.join(__dirname, 'views')));
app.use(function (req, res, next) {
res.render('index.html');
});
app.use( (req, res, next) => {
setTimeout(() => {
console.log(1);
}, 5000);
});
app.use((req,res,next) => {
setTimeout(() => {
console.log(2);
},2000);
})
http.createServer(app).listen(3001, function () {
console.log('start at 3001');
});