-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (57 loc) · 1.85 KB
/
index.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
var fs = require('fs');
var path = require('path');
var nunjucks = require('nunjucks');
var nunjucksComponentExtension = require('nunjucks-component-extension');
var extend = Object.assign || require('util')._extend;
function render(filePath) {
return new Promise(function (resolve, reject) {
fs.exists(filePath, function (exists) {
if (exists) {
nunjucks.render(filePath, function (err, str) {
if (err) {
reject(err);
} else {
resolve(str);
}
});
} else {
reject();
}
});
});
}
module.exports = function (viewPath, options) {
if (!viewPath) {
throw new Error('viewPath is required!')
}
var env = new nunjucks.configure(viewPath, extend({
watch: true,
noCache: true
}, options));
env.addExtension('ComponentExtension', nunjucksComponentExtension);
return function (req, res, next) {
var url = req.url;
var filePath = path.join(viewPath, url);
// 说明是.html后缀
if (path.extname(url) === '.html') {
render(filePath).then(function (str) {
var buf = new Buffer(str);
res.charset = res.charset || 'utf-8';
res.setHeader('Content-Type', res.getHeader('Content-Type') || 'text/html');
res.setHeader('Content-Length', buf.length);
res.end(buf);
}).catch(function (e) {
if (e) {
console.log(e.stack);
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end(e.stack);
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('404 error! File not found.');
}
});
} else {
next();
}
}
}