forked from shy2850/node-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
81 lines (80 loc) · 2.68 KB
/
Copy pathmiddleware.js
File metadata and controls
81 lines (80 loc) · 2.68 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
"use strict";
var mime = require("mime"),
cssmin = require("cssmin");
var mini = {
js: function(str, resp){
var resu = require("uglify-js").minify(str,{fromString: true});
resp.end( resu.code );
},
css: function(str, resp){ resp.end( cssmin(str)); },
htm: function(str, resp){ resp.end( str.replace(/\s+/g," ") ); },
get: function(pathname){
var extType = pathname.split('.').pop();
return function(str, resp){
var m = mini[extType];
if(m){
m(str, resp);
}else{
resp.end( str );
}
};
}
};
var middleware = {
coffee: function(req, resp, rs, pathname, DEBUG){
var scriptStr = require("coffee-script").compile( rs );
resp.writeHead(200, {"middleware-type": 'js', "Content-Type": mime.get('js')}); //用以build输出时转换后缀名
if(DEBUG){
resp.end( scriptStr );
}else{
mini.js(scriptStr, resp);
}
},
less: function(req, resp, rs, pathname, DEBUG){
require("less").render(rs, {
paths: [ pathname.replace(/(\/[^\/]+?)$/,"") ],
compress: !DEBUG
}, function (err, output) {
if (err) { throw err }
else{
resp.writeHead(200, {"middleware-type": 'css', "Content-Type": mime.get('css')});
resp.end( output.css );
}
});
},
jade: function(req, resp, rs){
resp.writeHead(200,{"middleware-type": 'html', "Content-Type": mime.get('html')});
var output = require('jade').render(rs);
resp.end( output );
},
md: function(req, resp, rs){
resp.writeHead(200,{"middleware-type": 'html', "Content-Type": mime.get('html')});
var output = require( "markdown" ).markdown.toHTML(rs + '');
resp.end( '<style>code{padding:2px 8px;background:#eee;}</style>' + output );
}
};
exports.get = function(pathname){
var extType = pathname.split('.').pop(),
fn = middleware[extType];
return !fn ? !1 : function(req, resp){
try{
fn.apply(middleware,arguments);
}catch(e){
resp.writeHead(500, {"Content-Type": "text/html"});
resp.end( JSON.stringify(e) );
}
};
};
exports.mini = mini;
mime.get = function(path, fallback){
if( /\bdo$/.test(path) ){
return this.lookup(path, fallback || "text/html");
}else if( /\bcur$/.test(path) ){
return "";
}else{
return this.lookup(path, fallback);
}
};
mime.isTXT = function(path, fallback){
return /\b(php|jsp|asp|less|coffee|jade)$/.test(path) || /\b(text|xml|javascript|json)\b/.test( this.get(path, fallback) );
};