UNPKG

3.19 kBJavaScriptView Raw
1var fs = require('co-fs');
2var thunkify = require('thunkify');
3var url = require('url');
4var path = require('path');
5
6var less = require('less');
7var stylus = require('stylus');
8var coffee = require('coffee-script');
9var babel = require('babel-core');
10
11/**
12 * 记得在static中间件之前使用,否则会被静态文件中间件处理
13 */
14exports.less = function (root) {
15 return function* (next) {
16 if (this.method === 'GET' || this.method === 'HEAD') {
17 var urlpath = this.request.path;
18 if (urlpath.match(/\.less$/)) {
19 var content;
20 try {
21 content = yield fs.readFile(path.join(root, urlpath), 'utf8');
22 } catch (ex) {
23 this.status = 404;
24 this.body = 'Cannot find ' + this.originalUrl + '\n';
25 return;
26 }
27 var result = yield less.render(content);
28 this.type = 'text/css';
29 this.body = result.css;
30 return;
31 }
32 }
33 yield* next;
34 };
35};
36
37var compileStylus = thunkify(function (str, callback) {
38 stylus(str).render(callback);
39});
40
41/**
42 * 记得在static中间件之前使用,否则会被静态文件中间件处理
43 */
44exports.stylus = function (root) {
45 return function* (next) {
46 if (this.method === 'GET' || this.method === 'HEAD') {
47 var urlpath = this.request.path;
48 if (urlpath.match(/\.styl$/)) {
49 var content;
50 try {
51 content = yield fs.readFile(path.join(root, urlpath), 'utf8');
52 } catch (ex) {
53 this.status = 404;
54 this.body = 'Cannot find ' + this.originalUrl + '\n';
55 return;
56 }
57 var result = yield compileStylus(content);
58 this.type = 'text/css';
59 this.body = result;
60 return;
61 }
62 }
63 yield* next;
64 };
65};
66
67/**
68 * 记得在static中间件之前使用,否则会被静态文件中间件处理
69 */
70exports.coffee = function (root) {
71 return function* (next) {
72 if (this.method === 'GET' || this.method === 'HEAD') {
73 var urlpath = this.request.path;
74 if (urlpath.match(/\.coffee$/)) {
75 var content;
76 try {
77 content = yield fs.readFile(path.join(root, urlpath), 'utf8');
78 } catch (ex) {
79 this.status = 404;
80 this.body = 'Cannot find ' + this.originalUrl + '\n';
81 return;
82 }
83 // 调用coffee-script编译源文件
84 var output = coffee.compile(content);
85 this.type = 'text/javascript';
86 this.body = output;
87 return;
88 }
89 }
90 yield* next;
91 };
92};
93
94exports.babel = function (root) {
95 return function* (next) {
96 if (this.method === 'GET' || this.method === 'HEAD') {
97 var urlpath = this.request.path;
98 if (urlpath.match(/\.es$/)) {
99 var content;
100 try {
101 content = yield fs.readFile(path.join(root, urlpath), 'utf8');
102 } catch (ex) {
103 this.status = 404;
104 this.body = 'Cannot find ' + this.originalUrl + '\n';
105 return;
106 }
107 // 调用coffee-script编译源文件
108 var output = babel.transform(content);
109 this.type = 'text/javascript';
110 this.body = output.code;
111 return;
112 }
113 }
114 yield* next;
115 };
116};