Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

v0.5.9 fixed some bugs and updated some methods

  • Loading branch information...
commit 7d5e79b348a18f518e8526ba28cffb89f28ac4e3 0 parents
@iwillwen authored
Showing with 20,413 additions and 0 deletions.
  1. +273 −0 README.md
  2. +295 −0 bin/webjs
  3. +21 −0 examples/math.js
  4. +32 −0 examples/play.js
  5. +64 −0 examples/reponsePipeling.js
  6. +17 −0 examples/sayhello-sex.js
  7. +54 −0 examples/sayhello.js
  8. +21 −0 examples/webjsoncoffee.coffee
  9. +12 −0 index.js
  10. +18 −0 lib/error/error.jade
  11. +37 −0 lib/httpstatus.js
  12. +13 −0 lib/index.js
  13. +717 −0 lib/method.js
  14. +53 −0 lib/middlewares/compiler.js
  15. +129 −0 lib/middlewares/compress.js
  16. +16 −0 lib/middlewares/patch.js
  17. +54 −0 lib/middlewares/router.js
  18. +262 −0 lib/middlewares/static.js
  19. +1,579 −0 lib/mimes.js
  20. +35 −0 lib/net.js
  21. +76 −0 lib/request.js
  22. +566 −0 lib/response.js
  23. +587 −0 lib/utils.js
  24. +1 −0  node_modules/.bin/jade
  25. +6 −0 node_modules/.bin/jade.cmd
  26. +63 −0 node_modules/asynclist/index.js
  27. +24 −0 node_modules/asynclist/package.json
  28. +25 −0 node_modules/bufferhelper/README.md
  29. +61 −0 node_modules/bufferhelper/bufferhelper.js
  30. +24 −0 node_modules/bufferhelper/package.json
  31. +4 −0 node_modules/commander/.npmignore
  32. +58 −0 node_modules/commander/History.md
  33. +7 −0 node_modules/commander/Makefile
  34. +260 −0 node_modules/commander/Readme.md
  35. +2 −0  node_modules/commander/index.js
  36. +908 −0 node_modules/commander/lib/commander.js
  37. +31 −0 node_modules/commander/package.json
  38. +12 −0 node_modules/connect/.npmignore
  39. +24 −0 node_modules/connect/LICENSE
  40. +4 −0 node_modules/connect/index.js
  41. +81 −0 node_modules/connect/lib/cache.js
  42. +93 −0 node_modules/connect/lib/connect.js
  43. +50 −0 node_modules/connect/lib/index.js
  44. +101 −0 node_modules/connect/lib/middleware/basicAuth.js
  45. +61 −0 node_modules/connect/lib/middleware/bodyParser.js
  46. +142 −0 node_modules/connect/lib/middleware/compress.js
  47. +62 −0 node_modules/connect/lib/middleware/cookieParser.js
  48. +118 −0 node_modules/connect/lib/middleware/cookieSession.js
  49. +73 −0 node_modules/connect/lib/middleware/csrf.js
  50. +229 −0 node_modules/connect/lib/middleware/directory.js
  51. +87 −0 node_modules/connect/lib/middleware/errorHandler.js
  52. +81 −0 node_modules/connect/lib/middleware/favicon.js
  53. +80 −0 node_modules/connect/lib/middleware/json.js
  54. +55 −0 node_modules/connect/lib/middleware/limit.js
  55. +337 −0 node_modules/connect/lib/middleware/logger.js
  56. +40 −0 node_modules/connect/lib/middleware/methodOverride.js
  57. +120 −0 node_modules/connect/lib/middleware/multipart.js
  58. +46 −0 node_modules/connect/lib/middleware/query.js
  59. +32 −0 node_modules/connect/lib/middleware/responseTime.js
  60. +344 −0 node_modules/connect/lib/middleware/session.js
  61. +128 −0 node_modules/connect/lib/middleware/session/cookie.js
  62. +131 −0 node_modules/connect/lib/middleware/session/memory.js
  63. +116 −0 node_modules/connect/lib/middleware/session/session.js
  64. +86 −0 node_modules/connect/lib/middleware/session/store.js
  65. +94 −0 node_modules/connect/lib/middleware/static.js
  66. +234 −0 node_modules/connect/lib/middleware/staticCache.js
  67. +45 −0 node_modules/connect/lib/middleware/timeout.js
  68. +76 −0 node_modules/connect/lib/middleware/urlencoded.js
  69. +40 −0 node_modules/connect/lib/middleware/vhost.js
  70. +79 −0 node_modules/connect/lib/patch.js
  71. +230 −0 node_modules/connect/lib/proto.js
  72. +75 −0 node_modules/connect/lib/public/directory.html
  73. +13 −0 node_modules/connect/lib/public/error.html
  74. BIN  node_modules/connect/lib/public/favicon.ico
  75. BIN  node_modules/connect/lib/public/icons/page.png
  76. BIN  node_modules/connect/lib/public/icons/page_add.png
  77. BIN  node_modules/connect/lib/public/icons/page_attach.png
  78. BIN  node_modules/connect/lib/public/icons/page_code.png
  79. BIN  node_modules/connect/lib/public/icons/page_copy.png
  80. BIN  node_modules/connect/lib/public/icons/page_delete.png
  81. BIN  node_modules/connect/lib/public/icons/page_edit.png
  82. BIN  node_modules/connect/lib/public/icons/page_error.png
  83. BIN  node_modules/connect/lib/public/icons/page_excel.png
  84. BIN  node_modules/connect/lib/public/icons/page_find.png
  85. BIN  node_modules/connect/lib/public/icons/page_gear.png
  86. BIN  node_modules/connect/lib/public/icons/page_go.png
  87. BIN  node_modules/connect/lib/public/icons/page_green.png
  88. BIN  node_modules/connect/lib/public/icons/page_key.png
  89. BIN  node_modules/connect/lib/public/icons/page_lightning.png
  90. BIN  node_modules/connect/lib/public/icons/page_link.png
  91. BIN  node_modules/connect/lib/public/icons/page_paintbrush.png
  92. BIN  node_modules/connect/lib/public/icons/page_paste.png
  93. BIN  node_modules/connect/lib/public/icons/page_red.png
  94. BIN  node_modules/connect/lib/public/icons/page_refresh.png
  95. BIN  node_modules/connect/lib/public/icons/page_save.png
  96. BIN  node_modules/connect/lib/public/icons/page_white.png
  97. BIN  node_modules/connect/lib/public/icons/page_white_acrobat.png
  98. BIN  node_modules/connect/lib/public/icons/page_white_actionscript.png
  99. BIN  node_modules/connect/lib/public/icons/page_white_add.png
  100. BIN  node_modules/connect/lib/public/icons/page_white_c.png
  101. BIN  node_modules/connect/lib/public/icons/page_white_camera.png
  102. BIN  node_modules/connect/lib/public/icons/page_white_cd.png
  103. BIN  node_modules/connect/lib/public/icons/page_white_code.png
  104. BIN  node_modules/connect/lib/public/icons/page_white_code_red.png
  105. BIN  node_modules/connect/lib/public/icons/page_white_coldfusion.png
  106. BIN  node_modules/connect/lib/public/icons/page_white_compressed.png
  107. BIN  node_modules/connect/lib/public/icons/page_white_copy.png
  108. BIN  node_modules/connect/lib/public/icons/page_white_cplusplus.png
  109. BIN  node_modules/connect/lib/public/icons/page_white_csharp.png
  110. BIN  node_modules/connect/lib/public/icons/page_white_cup.png
  111. BIN  node_modules/connect/lib/public/icons/page_white_database.png
  112. BIN  node_modules/connect/lib/public/icons/page_white_delete.png
  113. BIN  node_modules/connect/lib/public/icons/page_white_dvd.png
  114. BIN  node_modules/connect/lib/public/icons/page_white_edit.png
  115. BIN  node_modules/connect/lib/public/icons/page_white_error.png
  116. BIN  node_modules/connect/lib/public/icons/page_white_excel.png
  117. BIN  node_modules/connect/lib/public/icons/page_white_find.png
  118. BIN  node_modules/connect/lib/public/icons/page_white_flash.png
  119. BIN  node_modules/connect/lib/public/icons/page_white_freehand.png
  120. BIN  node_modules/connect/lib/public/icons/page_white_gear.png
  121. BIN  node_modules/connect/lib/public/icons/page_white_get.png
  122. BIN  node_modules/connect/lib/public/icons/page_white_go.png
  123. BIN  node_modules/connect/lib/public/icons/page_white_h.png
  124. BIN  node_modules/connect/lib/public/icons/page_white_horizontal.png
  125. BIN  node_modules/connect/lib/public/icons/page_white_key.png
  126. BIN  node_modules/connect/lib/public/icons/page_white_lightning.png
  127. BIN  node_modules/connect/lib/public/icons/page_white_link.png
  128. BIN  node_modules/connect/lib/public/icons/page_white_magnify.png
  129. BIN  node_modules/connect/lib/public/icons/page_white_medal.png
  130. BIN  node_modules/connect/lib/public/icons/page_white_office.png
  131. BIN  node_modules/connect/lib/public/icons/page_white_paint.png
  132. BIN  node_modules/connect/lib/public/icons/page_white_paintbrush.png
  133. BIN  node_modules/connect/lib/public/icons/page_white_paste.png
  134. BIN  node_modules/connect/lib/public/icons/page_white_php.png
  135. BIN  node_modules/connect/lib/public/icons/page_white_picture.png
  136. BIN  node_modules/connect/lib/public/icons/page_white_powerpoint.png
  137. BIN  node_modules/connect/lib/public/icons/page_white_put.png
  138. BIN  node_modules/connect/lib/public/icons/page_white_ruby.png
  139. BIN  node_modules/connect/lib/public/icons/page_white_stack.png
  140. BIN  node_modules/connect/lib/public/icons/page_white_star.png
  141. BIN  node_modules/connect/lib/public/icons/page_white_swoosh.png
  142. BIN  node_modules/connect/lib/public/icons/page_white_text.png
  143. BIN  node_modules/connect/lib/public/icons/page_white_text_width.png
  144. BIN  node_modules/connect/lib/public/icons/page_white_tux.png
  145. BIN  node_modules/connect/lib/public/icons/page_white_vector.png
  146. BIN  node_modules/connect/lib/public/icons/page_white_visualstudio.png
  147. BIN  node_modules/connect/lib/public/icons/page_white_width.png
  148. BIN  node_modules/connect/lib/public/icons/page_white_word.png
  149. BIN  node_modules/connect/lib/public/icons/page_white_world.png
  150. BIN  node_modules/connect/lib/public/icons/page_white_wrench.png
  151. BIN  node_modules/connect/lib/public/icons/page_white_zip.png
  152. BIN  node_modules/connect/lib/public/icons/page_word.png
  153. BIN  node_modules/connect/lib/public/icons/page_world.png
  154. +141 −0 node_modules/connect/lib/public/style.css
  155. +373 −0 node_modules/connect/lib/utils.js
  156. +1 −0  node_modules/connect/node_modules/bytes/.npmignore
  157. +5 −0 node_modules/connect/node_modules/bytes/History.md
  158. +7 −0 node_modules/connect/node_modules/bytes/Makefile
  159. +51 −0 node_modules/connect/node_modules/bytes/Readme.md
  160. +7 −0 node_modules/connect/node_modules/bytes/component.json
  161. +39 −0 node_modules/connect/node_modules/bytes/index.js
  162. +26 −0 node_modules/connect/node_modules/bytes/package.json
  163. +1 −0  node_modules/connect/node_modules/cookie/.npmignore
  164. +3 −0  node_modules/connect/node_modules/cookie/.travis.yml
  165. +44 −0 node_modules/connect/node_modules/cookie/README.md
  166. +57 −0 node_modules/connect/node_modules/cookie/index.js
  167. +35 −0 node_modules/connect/node_modules/cookie/package.json
  168. +1 −0  node_modules/connect/node_modules/cookie/test/mocha.opts
  169. +25 −0 node_modules/connect/node_modules/cookie/test/parse.js
  170. +59 −0 node_modules/connect/node_modules/cookie/test/serialize.js
  171. +4 −0 node_modules/connect/node_modules/debug/.npmignore
  172. +47 −0 node_modules/connect/node_modules/debug/History.md
  173. +4 −0 node_modules/connect/node_modules/debug/Makefile
  174. +130 −0 node_modules/connect/node_modules/debug/Readme.md
  175. +120 −0 node_modules/connect/node_modules/debug/debug.component.js
  176. +116 −0 node_modules/connect/node_modules/debug/debug.js
  177. +19 −0 node_modules/connect/node_modules/debug/example/app.js
  178. +24 −0 node_modules/connect/node_modules/debug/example/browser.html
  179. +10 −0 node_modules/connect/node_modules/debug/example/wildcards.js
  180. +22 −0 node_modules/connect/node_modules/debug/example/worker.js
  181. +1 −0  node_modules/connect/node_modules/debug/head.js
  182. +2 −0  node_modules/connect/node_modules/debug/index.js
  183. +135 −0 node_modules/connect/node_modules/debug/lib/debug.js
  184. +30 −0 node_modules/connect/node_modules/debug/package.json
  185. +4 −0 node_modules/connect/node_modules/debug/tail.js
  186. +4 −0 node_modules/connect/node_modules/formidable/.npmignore
  187. +4 −0 node_modules/connect/node_modules/formidable/.travis.yml
  188. +14 −0 node_modules/connect/node_modules/formidable/Makefile
  189. +311 −0 node_modules/connect/node_modules/formidable/Readme.md
  190. +3 −0  node_modules/connect/node_modules/formidable/TODO
  191. +70 −0 node_modules/connect/node_modules/formidable/benchmark/bench-multipart-parser.js
  192. +43 −0 node_modules/connect/node_modules/formidable/example/post.js
  193. +48 −0 node_modules/connect/node_modules/formidable/example/upload.js
  194. +1 −0  node_modules/connect/node_modules/formidable/index.js
  195. +73 −0 node_modules/connect/node_modules/formidable/lib/file.js
  196. +384 −0 node_modules/connect/node_modules/formidable/lib/incoming_form.js
  197. +3 −0  node_modules/connect/node_modules/formidable/lib/index.js
  198. +312 −0 node_modules/connect/node_modules/formidable/lib/multipart_parser.js
  199. +25 −0 node_modules/connect/node_modules/formidable/lib/querystring_parser.js
  200. +6 −0 node_modules/connect/node_modules/formidable/lib/util.js
  201. +4 −0 node_modules/connect/node_modules/formidable/node-gently/Makefile
  202. +167 −0 node_modules/connect/node_modules/formidable/node-gently/Readme.md
  203. +22 −0 node_modules/connect/node_modules/formidable/node-gently/example/dog.js
  204. +11 −0 node_modules/connect/node_modules/formidable/node-gently/example/event_emitter.js
  205. +1 −0  node_modules/connect/node_modules/formidable/node-gently/index.js
  206. +184 −0 node_modules/connect/node_modules/formidable/node-gently/lib/gently/gently.js
  207. +1 −0  node_modules/connect/node_modules/formidable/node-gently/lib/gently/index.js
  208. +14 −0 node_modules/connect/node_modules/formidable/node-gently/package.json
  209. +8 −0 node_modules/connect/node_modules/formidable/node-gently/test/common.js
  210. +348 −0 node_modules/connect/node_modules/formidable/node-gently/test/simple/test-gently.js
  211. +28 −0 node_modules/connect/node_modules/formidable/package.json
  212. +19 −0 node_modules/connect/node_modules/formidable/test/common.js
  213. +1 −0  node_modules/connect/node_modules/formidable/test/fixture/file/funkyfilename.txt
  214. +1 −0  node_modules/connect/node_modules/formidable/test/fixture/file/plain.txt
  215. +3 −0  node_modules/connect/node_modules/formidable/test/fixture/http/special-chars-in-filename/info.md
  216. +3 −0  node_modules/connect/node_modules/formidable/test/fixture/js/no-filename.js
  217. +21 −0 node_modules/connect/node_modules/formidable/test/fixture/js/special-chars-in-filename.js
  218. +72 −0 node_modules/connect/node_modules/formidable/test/fixture/multipart.js
  219. +89 −0 node_modules/connect/node_modules/formidable/test/integration/test-fixtures.js
  220. +24 −0 node_modules/connect/node_modules/formidable/test/legacy/common.js
  221. +80 −0 node_modules/connect/node_modules/formidable/test/legacy/integration/test-multipart-parser.js
  222. +104 −0 node_modules/connect/node_modules/formidable/test/legacy/simple/test-file.js
  223. +727 −0 node_modules/connect/node_modules/formidable/test/legacy/simple/test-incoming-form.js
  224. +50 −0 node_modules/connect/node_modules/formidable/test/legacy/simple/test-multipart-parser.js
  225. +45 −0 node_modules/connect/node_modules/formidable/test/legacy/simple/test-querystring-parser.js
  226. +75 −0 node_modules/connect/node_modules/formidable/test/legacy/system/test-multi-video-upload.js
  227. +2 −0  node_modules/connect/node_modules/formidable/test/run.js
  228. +63 −0 node_modules/connect/node_modules/formidable/test/unit/test-incoming-form.js
  229. +47 −0 node_modules/connect/node_modules/formidable/tool/record.js
  230. +1 −0  node_modules/connect/node_modules/fresh/.npmignore
  231. +7 −0 node_modules/connect/node_modules/fresh/Makefile
  232. +32 −0 node_modules/connect/node_modules/fresh/Readme.md
  233. +49 −0 node_modules/connect/node_modules/fresh/index.js
  234. +21 −0 node_modules/connect/node_modules/fresh/package.json
  235. +4 −0 node_modules/connect/node_modules/pause/.npmignore
  236. +5 −0 node_modules/connect/node_modules/pause/History.md
  237. +7 −0 node_modules/connect/node_modules/pause/Makefile
  238. +29 −0 node_modules/connect/node_modules/pause/Readme.md
  239. +29 −0 node_modules/connect/node_modules/pause/index.js
  240. +21 −0 node_modules/connect/node_modules/pause/package.json
  241. +6 −0 node_modules/connect/node_modules/qs/.gitmodules
  242. +1 −0  node_modules/connect/node_modules/qs/.npmignore
  243. +4 −0 node_modules/connect/node_modules/qs/.travis.yml
  244. +73 −0 node_modules/connect/node_modules/qs/History.md
  245. +5 −0 node_modules/connect/node_modules/qs/Makefile
  246. +54 −0 node_modules/connect/node_modules/qs/Readme.md
  247. +17 −0 node_modules/connect/node_modules/qs/benchmark.js
  248. +51 −0 node_modules/connect/node_modules/qs/examples.js
  249. +2 −0  node_modules/connect/node_modules/qs/index.js
  250. +264 −0 node_modules/connect/node_modules/qs/lib/querystring.js
  251. +27 −0 node_modules/connect/node_modules/qs/package.json
  252. +2 −0  node_modules/connect/node_modules/qs/test/mocha.opts
  253. +167 −0 node_modules/connect/node_modules/qs/test/parse.js
  254. +103 −0 node_modules/connect/node_modules/qs/test/stringify.js
  255. +4 −0 node_modules/connect/node_modules/send/.npmignore
  256. +20 −0 node_modules/connect/node_modules/send/History.md
  257. +8 −0 node_modules/connect/node_modules/send/Makefile
  258. +123 −0 node_modules/connect/node_modules/send/Readme.md
  259. +2 −0  node_modules/connect/node_modules/send/index.js
  260. +462 −0 node_modules/connect/node_modules/send/lib/send.js
  261. +47 −0 node_modules/connect/node_modules/send/lib/utils.js
  262. +19 −0 node_modules/connect/node_modules/send/node_modules/mime/LICENSE
  263. +63 −0 node_modules/connect/node_modules/send/node_modules/mime/README.md
  264. +104 −0 node_modules/connect/node_modules/send/node_modules/mime/mime.js
  265. +34 −0 node_modules/connect/node_modules/send/node_modules/mime/package.json
  266. +55 −0 node_modules/connect/node_modules/send/node_modules/mime/test.js
  267. +1,510 −0 node_modules/connect/node_modules/send/node_modules/mime/types/mime.types
  268. +65 −0 node_modules/connect/node_modules/send/node_modules/mime/types/node.types
  269. +1 −0  node_modules/connect/node_modules/send/node_modules/range-parser/.npmignore
  270. +15 −0 node_modules/connect/node_modules/send/node_modules/range-parser/History.md
  271. +7 −0 node_modules/connect/node_modules/send/node_modules/range-parser/Makefile
  272. +28 −0 node_modules/connect/node_modules/send/node_modules/range-parser/Readme.md
  273. +49 −0 node_modules/connect/node_modules/send/node_modules/range-parser/index.js
  274. +21 −0 node_modules/connect/node_modules/send/node_modules/range-parser/package.json
  275. +35 −0 node_modules/connect/node_modules/send/package.json
  276. +47 −0 node_modules/connect/package.json
  277. +11 −0 node_modules/connect/test.js
  278. +3 −0  node_modules/crc/.gitmodules
  279. +1 −0  node_modules/crc/.npmignore
  280. +7 −0 node_modules/crc/Makefile
  281. +31 −0 node_modules/crc/README.md
  282. +403 −0 node_modules/crc/lib/crc.js
  283. +24 −0 node_modules/crc/package.json
  284. +63 −0 node_modules/crc/test/crc.js
  285. +15 −0 node_modules/dataStream/.npmignore
  286. +4 −0 node_modules/dataStream/README.md
  287. +78 −0 node_modules/dataStream/index.js
  288. +33 −0 node_modules/dataStream/package.json
  289. 0  node_modules/ejs/.gitmodules
  290. +4 −0 node_modules/ejs/.npmignore
  291. +119 −0 node_modules/ejs/History.md
  292. +24 −0 node_modules/ejs/Makefile
  293. +168 −0 node_modules/ejs/Readme.md
  294. +14 −0 node_modules/ejs/benchmark.js
  295. +581 −0 node_modules/ejs/ejs.js
  296. +1 −0  node_modules/ejs/ejs.min.js
  297. +24 −0 node_modules/ejs/examples/client.html
  298. +7 −0 node_modules/ejs/examples/list.ejs
  299. +14 −0 node_modules/ejs/examples/list.js
  300. +2 −0  node_modules/ejs/index.js
Sorry, we could not display the entire diff because too many files (630) changed.
273 README.md
@@ -0,0 +1,273 @@
+# webjs: Simple HTTP / TCP development framework.
+
+For detailed information about this, please visit the [webjs homepage](http://web.c61.me). 如果想获得详细的关于Web.js的信息,请浏览[官方网站](http://web.c61.me)。
+
+# Install
+ $ npm install webjs
+
+or
+
+
+ $ npm install webjs@latest
+
+# App Demo
+ $ webjs -h
+
+ $ webjs init --all
+
+# Quick Start
+
+ var web = require('webjs');
+
+ var urlRouter = { //Url Router(inclube file and 302 jump) URL路由功能(包括文件映射和域名跳转)
+ '/:id.html' : 'page.html', //Return the 'page.html' data. 返回 'page.html' 的数据。(支持正则表达式)
+ '/google' : 'http://www.google.com' //When the path name is 'google', the browser will redirect to Google homepage. 当访问/google时,浏览器自动跳转到Google首页。
+ };
+ var getRouter = { //Get Method Router and handler GET方法服务器响应
+ '/getsomething' : function (req, res) {
+ for (var key in req.qs) {
+ res.send(key + ' : ' + req.qs[key], true); //res.send 方法接受两个参数,第一个是需要传输的数据,第二个是确定是否保持通讯不中断,以供继续传输。
+ }
+ res.send('That all');
+ }
+ };
+ var postRouter = {
+ '/postsomething' : function (req, res) { //Post Method Router and handler POST方法服务器响应
+ res.send('Post success<br />' + JSON.stringify(req.data));
+ }
+ };
+ web.run() //Run the first http server 启动首个服务器
+ .url(urlRouter) //Set the url router 传入URL映射规则
+ .get(getRouter) //Set the get method router 传入GET方法规则
+ .post(postRouter) //Set the post method router 传入POST方法规则
+ .use(web.bodyParser()); //Use the Body Parser
+
+# Simple Deployment 简单化部署
+
+如果你只想在某个文件夹内建立一个简单的文件服务器,那是非常简单的。 If you only want to deploy a simple file server, that's very easy!
+
+
+ var web = require('webjs').run();
+ web.use(web.static(__dirname));
+
+or
+
+
+ var app = require('webjs').create('http').listen();
+ app.use(app.bodyParser());
+
+Yes! It's so cool!
+没错的,就是这么简单。
+
+# Url Router URL路由映射
+
+## Web.js supports a Url Router which is very easy to use. Web.js提供了十分简单的URL路由映射方法
+
+
+ var web = require('webjs');
+
+ var urlRouter = {
+ '/:year/:mouth/:day/:id.jpg' : '$1-$2-$3-$4.jpg', // YYYY/MM/DD/NUM.jpg -> YYYY-MM-DD-NUM.jpg
+ '/:action' : 'main.html?action=$1' // /get -> main.html?action=get
+ };
+ web.run(8888)
+ .url(urlRouter);
+
+# HTTP Mothod HTTP方法
+
+## GET
+
+ var web = require('webjs');
+
+ var getRouter = {
+ '/getQuerystring' : function (req, res) { //Set two arguments, they're request and response. 传入两个参数,分别为Request, Response
+ res.sendJSON(req.qs); //The first argument can be an Array, an Object or a String. res.sendJSON()方法可以直接传入Array, Object, String的JSON对象
+ },
+ '/getQueryURL' : function (req, res) {
+ res.send(req.url); //The first argument must be a String. res.send()方法可以只能传入String数据
+ },
+ '/getFile' : function (req, res) {
+ res.sendFile(req.qs.file); //The first argument must be a file path.(it needn't begins with './') res.sendFile()方法只能传入含有文件名的String对象,不需要'./'
+ }
+ };
+
+ web.run(8888) //Set a empty url router. 传入空URL路由规则
+ .get(getRouter); //Set the get router. 传入GET方法规则
+
+## POST
+
+
+ var web = require('webjs');
+
+ var postRouter = {
+ '/postHello' : function (req, res) { //The post router is same to the get router. 与GET方法规则相同
+ res.send('Hello ' + req.data.name + '!');
+ }
+ };
+
+ web.run(8888)
+ .post(postRouter) //Set the post router. 传入POST方法规则
+ .use(web.bodyParser());
+
+## 其他HTTP方法
+
+The others http method's usages are same to get router.
+
+
+ var web = require('webjs');
+
+ var putRouter = {
+ '/putHello' : function (req, res) {
+ res.send('Hello ' + req.data.name + '!');
+ }
+ };
+
+ web.run(8888)
+ .put(postRouter)
+ .use(web.bodyParser());
+
+
+## HTTPS
+
+Https's usage is same to http's.
+HTTPS方法与HTTP方法相同
+
+
+ var web = require('webjs');
+ var urlRouter = {
+ '/:id.html' : 'page.html',
+ '/google' : 'http://www.google.com'
+ };
+ var getRouter = {
+ '/getQuerystring' : function (req, res) {
+ res.sendJSON(req.qs);
+ },
+ '/getQueryURL' : function (req, res) {
+ res.send(req.url);
+ },
+ '/getFile' : function (req, res) {
+ res.sendFile(req.qs.file);
+ }
+ };
+ var postRouter = {
+ '/postHello' : function (req, res) {
+ res.send('Hello ' + req.data.name + '!');
+ }
+ };
+ web.runHttps(8888)
+ .url(urlRouter)
+ .get(getRouter)
+ .post(postRouter);
+
+## Response Pipelining
+
+通过Response Pipelining,你可以对即将发送至客户端的数据进行处理,如压缩、解析等等。
+You can use this to edit the data will be sent to the client. Such as compress, compile.
+
+ var web = require('webjs');
+ var zlib = require('zlib');
+ web.run()
+ .use(
+ web.static(__dirname + '/static'),
+ function (req, res, next) {
+
+ // collect data
+
+ res.__defineGetter__('data', function () {
+ return function (data) {
+ this.data = data;
+ }
+ })
+
+ // Working
+ res.on('pipelining', function () {
+ switch (this.data.type) {
+ case "one":
+ // do something
+ }
+ });
+
+ next();
+ }
+ );
+
+## 404 Page
+
+ web.setErrorPage(404, __dirname + '/404.html'); //Set a file path. 传入一个文件名
+
+
+## Middleware 中间件
+
+Web.js supports the middleware.
+支持中间件,支持express和connect所有的中间件。
+
+
+ var web = require('webjs');
+
+ web.run()
+ .use(
+ web.bodyParser(),
+ web.cookieParser('webjs'),
+ web.session(),
+ web.compress(),
+ web.complier({ enable: ["less", "sass"] }),
+ web.static(__dirname + '/static')
+ );
+
+
+# webjs plugin
+
+Web.js supports a very cool plugin mechanism.
+
+## Modular functions
+
+You can use it to modular your app functions.
+
+
+ module.exports = function (web) {
+ web.get({
+ '/some': function (req, res) {
+ res.send('some');
+ }
+ });
+ }
+
+## Custom functions
+
+
+ module.exports = function (web) {
+ web.__defineGetter__('foo', function () {
+ return this.servers;
+ });
+
+ // or
+ web.fn('bar', funtion () {
+ // do something
+ });
+ }
+
+
+# License
+
+(The MIT License)
+
+Copyright (c) 2010-2012 Will Wen Gunn (甘超阳) &lt;willwengunn@gmail.com&gt;
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+'Software'), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
295 bin/webjs
@@ -0,0 +1,295 @@
+#!/usr/bin/env node
+
+//CLI
+
+var web = require('webjs');
+var program = require('commander');
+var mkdirp = require('mkdirp');
+var fs = require('fs');
+var asynclist = require('asynclist');
+program
+ .version(web.version)
+ .usage('[option] <value..>')
+ .option('-c, --cookie', 'Add cookie support')
+ .option('-s, --session', 'Add session support')
+ .option('-b, --body', 'Add body parser support')
+ .option('--compress', 'Add compress support')
+ .option('--compiler <engine>', 'Add compiler support', list)
+ .option('-r, --rest', 'Add more HTTP methods support')
+ .option('--mustache', 'Add mustache template engine support (defaults to jade)')
+ .option('--ejs', 'Add ejs template engine support (defaults to jade)')
+ .option('--tmpl <engine>', 'Set the template engine')
+ .option('--mode <mode>', 'Set the mode (defaults to production)')
+ .option('--port <port>', 'Set the port (defaults to 80)')
+ .option('-a --all', 'Enable all functions')
+ .on('--help', function(){
+ console.log(' Examples:');
+ console.log('');
+ console.log(' $ webjs');
+ console.log(' $ webjs init -s -c -b -r --mode pro --port 8888 --compress --compiler less');
+ console.log(' $ webjs init --all');
+ console.log(' $ webjs run 8080');
+ console.log('');
+ });
+
+var path = program.args.shift() || '.';
+program
+ .command('run <port>')
+ .description('run a simple http server here')
+ .action(function (port) {
+ web.run(port)
+ .use(web.static(path));
+ });
+
+program
+ .command('init')
+ .description('Initialize a webjs app here')
+ .action(function () {
+ program.inite = true;
+ mkdir(path, function(){
+ //Public
+ var paths = [
+ path + '/static',
+ path + '/controllers',
+ path + '/models',
+ path + '/views',
+ path + '/static/js',
+ path + '/static/css'
+ ];
+ var list = paths.map(function (_path) {
+ return function () {
+ mkdir(_path, function () {
+ tasks.trigger(_path);
+ });
+ };
+ });
+ var tasks = new asynclist(list);
+ tasks.assign(function () {
+ var files = [
+ [path + '/static/css/style.css', css],
+ [path + '/static/css/style.less', less],
+ [path + '/static/index.html', index_html],
+ [path + '/controllers/index.js', index],
+ [path + '/controllers/router.js', router],
+ [path + '/views/hello.jade', hello],
+ [path + '/views/layout.jade', layout],
+ [path + '/server.js', server]
+ ];
+ var _list = files.map(function (file) {
+ return function () {
+ write(file[0], file[1], function () {
+ filesTasks.trigger(file);
+ });
+ };
+ });
+ var filesTasks = new asynclist(_list);
+ filesTasks.assign(function () {
+ console.log('Enjoy!');
+
+ if (program.compiler || program.all)
+ console.log('Please run \'npm install less sass\' to install the compilers.');
+ process.exit(1);
+ });
+ filesTasks.run();
+ });
+ tasks.run();
+ });
+ });
+program.parse(process.argv);
+program.template = 'jade';
+if (program.mustache) program.template = 'mustache';
+if (program.ejs) program.template = 'ejs';
+program.mode = program.mode || 'pro';
+if (!program.port) program.port = '';
+
+var index_html = [
+ '<!DOCTYPE html>',
+ '<html>',
+ ' <head>',
+ ' <title>webjs Quick Start</title>',
+ ' <link rel=\'stylesheet\' href=\'/css/style.' + (program.compiler || program.all ? 'less' : 'css') + '\' />',
+ ' </head>',
+ ' <body>',
+ ' <header>',
+ ' <h1>Thanks for using webjs</h1>',
+ ' </header>',
+ ' <section>',
+ ' <article>',
+ ' <p>Let\'s get start with webjs.</p> <button class="red"><a href="/hello" target="_top" class="label">Example</a></button>',
+ ' </article>',
+ ' </section>',
+ ' </body>',
+ '</html>'
+].join('\r\n');
+var css = [
+ 'body {',
+ ' padding: 50px;',
+ ' font: 30px Yanone Kaffeesatz, Lucida Grande, Mirosoft Yahei, Helvetica, Arial, sans-serif;',
+ '}',
+ '.red {',
+ ' border: 1px solid #c51236;',
+ ' background: #dc143c;',
+ ' background: -webkit-linear-gradient(top, #eb1f48, #dc143c);',
+ ' background: -moz-linear-gradient(top, #eb1f48, #dc143c);',
+ ' background: -ms-linear-gradient(top, #eb1f48, #dc143c);',
+ ' background: -o-linear-gradient(top, #eb1f48, #dc143c);',
+ ' -webkit-transition: all .20s;',
+ ' -moz-transition: all .20s;',
+ ' -o-transition: all .20s;',
+ ' transition: all .20s;',
+ ' cursor: pointer;',
+ ' margin: 5px;',
+ ' padding: 5px 6px 4px 6px;',
+ ' -webkit-border-radius: 2px;',
+ ' -moz-border-radius: 2px;',
+ ' border-radius: 2px;',
+ '}',
+ '.red:hover {',
+ ' border: 1px solid #b71132;',
+ ' background: #c51236;',
+ ' background: -webkit-linear-gradient(top, #eb1f48, #ce1338);',
+ ' background: -moz-linear-gradient(top, #eb1f48, #ce1338);',
+ ' background: -ms-linear-gradient(top, #eb1f48, #ce1338);',
+ ' background: -o-linear-gradient(top, #eb1f48, #ce1338);',
+ '}',
+ '.red .label {',
+ ' font-weight: bold;',
+ ' padding: 0 17px;',
+ ' color: #FFF;',
+ ' text-shadow: 0 1px 0 #ad102f;',
+ ' text-decoration: none;',
+ ' line-height: 15px;',
+ ' display: inline-block;',
+ ' height: 18px;',
+ ' overflow: hidden;',
+ ' -webkit-transition: color .20s;',
+ ' -moz-transition: color .20s;',
+ ' -o-transition: color .20s;',
+ ' transition: color .20s;',
+ '}'
+].join('\r\n');
+var less = [
+ 'body {',
+ ' padding: 50px;',
+ ' font: 30px Yanone Kaffeesatz, Lucida Grande, Mirosoft Yahei, Helvetica, Arial, sans-serif;',
+ '}',
+ '.jazz_button (@color: #F1F1F1) {',
+ ' @light: lighten(@color, 5%);',
+ ' @dark: darken(@color, 5%);',
+ ' @text_shadow: darken(@color, 10%);',
+ ' border: 1px solid @dark;',
+ ' background: @color;',
+ ' background: -webkit-linear-gradient(top, @light, @color);',
+ ' background: -moz-linear-gradient(top, @light, @color);',
+ ' background: -ms-linear-gradient(top, @light, @color);',
+ ' background: -o-linear-gradient(top, @light, @color);',
+ ' -webkit-transition: all .20s;',
+ ' -moz-transition: all .20s;',
+ ' -o-transition: all .20s;',
+ ' transition: all .20s;',
+ ' cursor: pointer;',
+ ' margin: 5px;',
+ ' padding: 5px 6px 4px 6px;',
+ ' -webkit-border-radius: 2px;',
+ ' -moz-border-radius: 2px;',
+ ' border-radius: 2px;',
+ ' &:hover {',
+ ' border: 1px solid darken(@dark, 3%);',
+ ' background: darken(@color, 5%);',
+ ' background: -webkit-linear-gradient(top, @light, darken(@color, 3%));',
+ ' background: -moz-linear-gradient(top, @light, darken(@color, 3%));',
+ ' background: -ms-linear-gradient(top, @light, darken(@color, 3%));',
+ ' background: -o-linear-gradient(top, @light, darken(@color, 3%));',
+ ' }',
+ ' .label {',
+ ' font-weight: bold;',
+ ' padding: 0 17px;',
+ ' color: #FFF;',
+ ' text-shadow: 0 1px 0 @text_shadow;',
+ ' text-decoration: none;',
+ ' line-height: 15px;',
+ ' display: inline-block;',
+ ' height: 18px;',
+ ' overflow: hidden;',
+ ' -webkit-transition: color .20s;',
+ ' -moz-transition: color .20s;',
+ ' -o-transition: color .20s;',
+ ' transition: color .20s;',
+ ' }',
+ '}',
+ '.red {',
+ ' .jazz_button(crimson);',
+ '}'
+].join('\r\n');
+var index = [
+ 'var web = require(\'webjs\');',
+ '',
+ 'web.run(' + program.port + ')',
+ ' .config({',
+ ' \'view engine\': \'' + program.template + '\',',
+ ' \'views\': __dirname + \'/../views\',',
+ (program.rest || program.all ? ' \'readonly\': false,' : ''),
+ (program.mode == 'dev' ? ' \'dbgPath\': __dirname + \'/..\',' : ''),
+ ' \'mode\': \'' + program.mode + '\'',
+ ' })',
+ ' .use(',
+ (program.cookie || program.all ? ' web.cookieParser(\'webjs\'),' : ''),
+ (program.session || program.all ? ' web.session(),' : ''),
+ (program.body || program.all ? ' web.bodyParser(),' : ''),
+ (program.compiler || program.all ? ' web.compiler({ enable: ' + JSON.stringify((program.compiler ? program.compiler : ["less", "sass"])) + ' }),' : ''),
+ (program.compress || program.all ? ' web.compress(),' : ''),
+ ' web.static(__dirname + \'/../static\')',
+ ' )',
+ ' .extend(__dirname + \'/router\');',
+ '',
+ 'console.log(\'The app is running!\');'
+].join('\r\n');
+var router = [
+ 'module.exports = function (web) {',
+ ' web.get(\'/hello\', function (req, res) {',
+ (program.session || program.all ? ' if (isNaN(req.session.times))\r\n req.session.times = 0\r\n else\r\n req.session.times++;' : ''),
+ ' res.render(\'hello\', {',
+ (program.session || program.all ? ' times: req.session.times,' : ''),
+ ' title: \'webjs\'',
+ ' });',
+ ' });',
+ '};'
+].join('\r\n');
+var server = [
+ 'require(__dirname + \'/controllers/\');'
+].join('\r\n');
+var hello = [
+ 'h1 Hello World!',
+ 'p Welcome to #{title}',
+ (program.session || program.all ? 'p You had refreshed #{times} times' : '')
+].join('\r\n');
+var layout = [
+ 'html',
+ ' head',
+ ' title= title',
+ ' link(type=\'text/css\', rel=\'stylesheet\', href=\'/css/style.' + (program.compiler || program.all ? 'less' : 'css') + '\')',
+ ' != body'
+].join('\r\n');
+
+function emptyDirectory (path, fn) {
+ fs.readdir(path, function(err, files){
+ if (err && 'ENOENT' != err.code) throw err;
+ fn(!files || !files.length);
+ });
+}
+function write (path, str, fn) {
+ fs.writeFile(path, str, function () {
+ console.log(' \x1b[36mcreate\x1b[0m : ' + path);
+ fn();
+ });
+}
+function mkdir (path, fn) {
+ mkdirp(path, 0755, function(err){
+ if (err) throw err;
+ console.log(' \033[36mcreate\033[0m : ' + path);
+ fn && fn();
+ });
+}
+function list (val) {
+ return val.split(',');
+}
21 examples/math.js
@@ -0,0 +1,21 @@
+var web = require('webjs');
+var getRouter = {
+ 'add/:a/:b': function (req, res) {
+ res.send(Number(req.path.a) + Number(req.path.b) + '');
+ },
+ 'sub/:a/:b': function (req, res) {
+ res.send(Number(req.path.a) - Number(req.path.b) + '');
+ },
+ 'mul/:a/:b': function (req, res) {
+ res.send(Number(req.path.a) * Number(req.path.b) + '');
+ },
+ 'div/:a/:b': function (req, res) {
+ res.send(Number(req.path.a) / Number(req.path.b) + '');
+ },
+ '/:path/:path/:id': function (req, res) {
+ res.send(req.path.id);
+ }
+};
+web.run(8888)
+ .get(getRouter);
+console.log('running');
32 examples/play.js
@@ -0,0 +1,32 @@
+var http = require('http');
+var asynclist = require('asynclist');
+
+var opts = {
+ host: '127.0.0.1'
+};
+var list = [];
+var succeed = 0;
+var failed = 0;
+for (var i = 0; i < 1001; i++) {
+ list.push(function () {
+ http.get(opts, function (res) {
+ res.on('end', function () {
+ succeed++;
+ tasks.trigger(true);
+ });
+ }).on('error', function (e) {
+ console.log('error!');
+ failed++;
+ tasks.trigger(false);
+ });
+ });
+}
+var timeout = 0;
+var timer = setInterval(function () {
+ timeout++;
+}, 1);
+var tasks = new asynclist(list);
+tasks.assign(function () {
+ clearInterval(timer);
+ console.log('Finished. Used time: ' + timeout + 'ms');
+}).run();
64 examples/reponsePipeling.js
@@ -0,0 +1,64 @@
+var web = require('webjs');
+
+// Custom stream class
+var dataStream = require('dataStream');
+
+web.run(8888)
+ .use(web.cookieParser('webjs'))
+ .use(web.session())
+
+ // Response Pipelining
+ .use(web.complier({ enable: ["less"] }))
+ .use(function (req, res, next) {
+
+ var render = function (body) {
+ // do something
+ };
+ var complieStream = new dataStream({ readable: false });
+
+ complieStream.on('complete', function () {
+ var body = this.body()/* Buffer */
+ .toString();
+
+ // empty the stream
+ this.empty();
+
+ // pipe data to the next stream
+ this.emit('data', render(body));
+ });
+
+ res.pipelining(function () {
+ return complieStream;
+ });
+
+ next();
+ })
+ .use(web.compress())
+ .use(function (req, res, next) {
+
+ // collect data
+
+ res.data = function (data) {
+ this.data = data;
+ }
+
+ // Working
+ res.on('pipelining', function () {
+ switch (this.data.type) {
+ case "one":
+ // do something
+ }
+ });
+
+ next();
+ })
+ .use(web.static(__dirname + '/../static'));
+
+ /**
+ *
+ * Pipeline
+ * Static -> Complier -> Custom Complier -> Compress -> Data Mining -> Response
+ *
+ */
+
+console.log('The app is running!');
17 examples/sayhello-sex.js
@@ -0,0 +1,17 @@
+var web = require('webjs');
+
+var getRouter = {
+ 'name/:sex': function (req, res) {
+ switch (req.query.sex) {
+ case 'woman':
+ res.send('Hi! Miss. ' + decodeURI(req.path[0]) + '! Nice to meet you.');
+ break;
+ case 'man':
+ default:
+ res.send('Hey! Mr. ' + decodeURI(req.path[0]) + '! Nice to meet you.');
+ }
+ }
+};
+web.run(8888)
+ .use(web.query())
+ .get(getRouter);
54 examples/sayhello.js
@@ -0,0 +1,54 @@
+var http = require('http');
+var web = require('./index.js');
+
+
+function ask () {
+ var req = http.request({
+ host: '127.0.0.1',
+ port: '45678',
+ path: '/getQuerystring',
+ method: 'get'
+ });
+
+ req.on('response',function (res) {
+ res.on('data',function (chunk) {
+ console.log('body:' + chunk);
+ });
+ });
+ req.end();
+}
+
+
+var getRouter = {
+ 'name/:name': function (req, res) {
+ res.send('Hey! Mr. ' + decodeURI(req.params.name) + '! Nice to meet you.');
+ },
+ 'getQuerystring' : function (req, res) {
+ res.sendJSON(req.query);
+ }
+};
+
+
+web.run(45678);
+ask();
+setTimeout(function () {
+ web.use(web.query)
+ .get(getRouter);
+ ask();
+}, 3000);
+
+var util = require('util'),
+ spawn = require('child_process').spawn,
+ ls = spawn('ls', ['-lh', '/usr']);
+
+ls.stdout.on('data', function (data) {
+ console.log('stdout: ' + data);
+});
+
+ls.stderr.on('data', function (data) {
+ console.log('stderr: ' + data);
+});
+
+ls.on('exit', function (code) {
+ console.log('child process exited with code ' + code);
+});
21 examples/webjsoncoffee.coffee
@@ -0,0 +1,21 @@
+web = require 'webjs'
+
+web.run(8888)
+ .config(
+ 'views': __dirname + '/../views'
+ 'view engine': 'jade'
+ 'mode': 'dev'
+ )
+ .use(
+ web.complier enable: ["less"]
+ do web.compress
+ '/public', web.static __dirname + '/..'
+ )
+
+web.get
+ '/hello': (req, res) ->
+ res.send 'Hello Green World!'
+ '/sayName': (req, res) ->
+ res.send 'I\'m the World!'
+
+console.log 'The app is runing!'
12 index.js
@@ -0,0 +1,12 @@
+/*
+ * @fileOverview
+ * @author Will Wen Gunn
+ * @version 0.5.9
+ */
+/*
+ * @constructor webjs
+ * @descripttion A simple HTTP, HTTPS and TCP framework for Node.js
+ * @see <a href="https://github.com/iwillwen/webjs">web.js on Github</a>
+ * @Simple Deployment require('webjs').run()
+ */
+module.exports = require('./lib/index');
18 lib/error/error.jade
@@ -0,0 +1,18 @@
+html
+ title= title
+ style
+ body {
+ padding: 100px;
+ font: 20px "Lucida Grande", Helvetica, Arial, sans-serif;
+ }
+ h1 {
+ font-size: 40px;
+ margin-bottom: -20px;
+ }
+ footer {
+ bottom: 15px;
+ position: absolute;
+ }
+ h2 webjs Error
+ h1= message
+ blockquote= stack
37 lib/httpstatus.js
@@ -0,0 +1,37 @@
+exports.status = {
+ '304': 'Not Modified',
+ '400': 'Bad Request',
+ '401': 'Unauthorized',
+ '402': 'Payment Required',
+ '403': 'Forbidden',
+ '404': 'Not Found',
+ '405': 'Method Not Allowed',
+ '406': 'Not Acceptable',
+ '407': 'Proxy Authentication Required',
+ '408': 'Request Timeout',
+ '409': 'Conflict',
+ '410': 'Gone',
+ '411': 'Length Required',
+ '412': 'Precondition Failed',
+ '413': 'Request Entity Too Large',
+ '414': 'Request-URI Too Long',
+ '415': 'Unsupported Media Type',
+ '416': 'Requested Range Not Satisfiable',
+ '417': 'Expectation Failed',
+ '421': 'There are too many connections from your internet address',
+ '422': 'Unprocessable Entity',
+ '424': 'Failed Dependency',
+ '425': 'Unordered Collection',
+ '426': 'Upgrade Required',
+ '449': 'Retry With',
+ '500': 'Internal Server Error',
+ '501': 'Not Implemented',
+ '502': 'Bad Gateway',
+ '503': 'Service Unavailable',
+ '504': 'Gateway Timeout',
+ '505': 'HTTP Version Not Supported',
+ '506': 'Variant Also Negotiate',
+ '507': 'Insufficient Storage',
+ '509': 'Bandwidth Limit Exceeded',
+ '510': 'Not Extended'
+};
13 lib/index.js
@@ -0,0 +1,13 @@
+//Metas
+var web = exports;
+web.servers = [];
+web.httpsServers = [];
+require('./method').ext(web);
+require('emitter')(web);
+
+global.__defineGetter__('web', function () {
+ return web;
+});
+global.__defineSetter__('web', function (_web) {
+ web = _web;
+});
717 lib/method.js
@@ -0,0 +1,717 @@
+//Modules
+var fs = require("fs");
+var pathmo = require('path');
+var util = require('util');
+//Foundation Server
+var connect = require('connect');
+var https = require('https');
+var http = require('http');
+var dataStream = require('dataStream');
+var eventproxy = require('eventproxy').EventProxy;
+var asynclist = require('asynclist');
+var url = require('url');
+var utils = require('./utils');
+var middlewares = ['basicAuth', 'bodyParser', 'cookieParser', 'cookieSession', 'csrf', 'directory', 'errorHandler', 'favicon', 'json', 'limit', 'logger', 'methodOverride', 'multipart', 'query', 'responseTime', 'session', 'staticCache', 'urlencoded', 'vhost'];
+function method (web) {
+
+ //Method
+ web.version = '0.5.9';
+
+ /**
+ * return a middlewaves collection iterator.
+ * @param {Function | Array} fn1 a middlewave or a collection of middlewaves
+ * @param {Function} fn2 Final handle
+ * @return {Function} a middlewaves collection iterator
+ *
+ * web.get('/',
+ * web._([
+ * function (req, res, next) {
+ * console.log('first middlewave');
+ * next();
+ * },
+ * function (req, res, next) {
+ * console.log('second middlewave');
+ * next();
+ * },
+ * function (req, res, next) {
+ * console.log('third middlewave');
+ * next();
+ * }],
+ * function (req, res) {
+ * res.send('Hello World');
+ * })
+ * );
+ *
+ */
+ web._ = function (fn1, fn2) {
+ if (!util.isArray(fn1)) fn1 = [fn1];
+ return function (req, res, out) {
+ var i = -1;
+ function next () {
+ i++;
+ var layer = fn1[i];
+
+ if (layer) {
+ layer(req, res, next);
+ } else {
+ fn2(req, res, out);
+ }
+ }
+ next();
+ }
+ };
+ /**
+ * HTTP/S server method setter.
+ * @param {String} method HTTP method
+ * @param {Function} handlers Request handlers
+ * @param {Object} server Server Object
+ * @return {Object} web controller
+ */
+ web.httpMethodHelper = function (method, handlers, server) {
+ var _server = typeof server == 'object' ? server : web.server;
+ _server = _server || web.httpsServer || this;
+
+ //Check if had use the router middleware
+ if (!_server.setRouter) {
+ _server.use.call(_server, web.router);
+ _server.setRouter = true;
+ }
+ switch (typeof handlers) {
+ /**
+ * web.get({ ... });
+ */
+ case 'object':
+ for(var key in handlers) {
+ web.httpMethodHelper(method, key, handlers[key]);
+ }
+ break;
+ /**
+ * web.get('/hello', function (req, res) { ... });
+ */
+ case 'string':
+ if (_server.handlers[method] === undefined && _server.handlers[method] === undefined) {
+ _server.handlers[method] = {};
+ _server.rules[method] = {};
+ }
+ _server.handlers[method][handlers] = server;
+ if (handlers !== '*') {
+ /**
+ * web.get('*', function (req, res) { //404 });
+ */
+ _server.rules[method][handlers] = new RegExp('^' + handlers.replace(/:([\w%$.-]*)/g, '([\\\w%$.-]*)').replace("(([\\\w%$.-]*))", '([\\\w%$.-]*)') + '$', 'i');
+ } else {
+ _server.rules[method][handlers] = /^([\/\w$%.-]*)$/i;
+ }
+ }
+ return this;
+ };
+ web.handlers = {};
+ web.rules = {};
+ /**
+ * Set a handle for every request. (Without routing)
+ * @param {String} method HTTP method
+ * @param {Function} method Request handle
+ * @return {Object} web controller
+ *
+ * web.route('get', function (req, res) {
+ * res.send('Hello World');
+ * });
+ *
+ */
+ web.route = function (method, handler) {
+ web.use(function (req, res, next) {
+ if (req.method.toLowerCase() !== method.toLowerCase()) return next();
+ web.patch(req, res, function () {
+ handler(req, res, next);
+ });
+ });
+ return this;
+ };
+ /**
+ * Set a get router to current server or specify server.
+ * @param {String | Object} _gethandlers | rule GetRouters or router's rule
+ * @param {Function | Object} handle | server router's handle or server object
+ * @return {Object} web controllers
+ *
+ * web.get('/:name', function (req, res) {
+ * res.send('Hello ' + req.param.name + '!');
+ * });
+ *
+ * web.get('/:name', checkAuth, function (req, res) {
+ * res.send('Hello ' + req.param.name + '!');
+ * });
+ *
+ * //Middlewave
+ * function checkAuth (req, res, next) {
+ *
+ * }
+ *
+ */
+ web.get = function (_gethandlers, server, fn) {
+ if (fn) {
+ return this.httpMethodHelper('get', _gethandlers, web._(server, fn));
+ } else {
+ return this.httpMethodHelper('get', _gethandlers, server);
+ }
+ };
+ /**
+ * Set a post router to current server or specify server.
+ * @param {String | Object} _posthandlers | rule PostRouters or router's rule
+ * @param {Function | Object} handle | server router's handle or server object
+ * @return {Object} web controllers
+ *
+ * web.post('/new', function (req, res) {
+ *
+ * })
+ *
+ */
+ web.post = function (_posthandlers, server, fn) {
+ if (fn) {
+ return this.httpMethodHelper('post', _posthandlers, web._(server, fn));
+ } else {
+ return this.httpMethodHelper('post', _posthandlers, server);
+ }
+ };
+ /**
+ * Set a post router to current server or specify server.
+ * @param {String | Object} _posthandlers | rule PostRouters or router's rule
+ * @param {Function | Object} handle | server router's handle or server object
+ * @return {Object} web controllers
+ */
+ web.put = function (_puthandlers, server, fn) {
+ if (fn) {
+ return this.httpMethodHelper('put', _puthandlers, web._(server, fn));
+ } else {
+ return this.httpMethodHelper('put', _puthandlers, server);
+ }
+ };
+
+ web.delete = function (_deletehandlers, server) {
+ return this.httpMethodHelper('delete', _deletehandlers, server);
+ };
+ web.del = web.delete;
+ web.head = function (_headhandlers, server) {
+ return this.httpMethodHelper('head', _headhandlers, server);
+ };
+ /*
+ * @description Set a UrlRouter to current server or specify server. 设置当前或指定的Server的PostRouter
+ * @param {Object} _posthandlers A UrlRouter or a UrlRule key.(require) 传入的PostRouter或是一个规则的key.*
+ * @param {Object} server Specify server or a UrlRule origin. 可指定Server
+ */
+ web.url = function (_urlhandlers, server) {
+ //Jump url
+ if (typeof _urlhandlers == 'string') {
+ var origin = server;
+ server = function (req, res) {
+ res.redirect(origin);
+ }
+ } else {
+ for (var key in _urlhandlers) {
+ var origin = _urlhandlers[key];
+ _urlhandlers[key] = function (req, res) {
+ res.redirect(origin);
+ }
+ }
+ }
+ return this.httpMethodHelper('get', _urlhandlers, server);
+ };
+ /*
+ * @description 设置GET和POST响应错误时的错误响应
+ * @param {Object} handlers 传入的ErorrHandlers*
+ */
+ web.error = function (handlers, server) {
+ var _server = typeof server == 'object' ? server : web.server;
+ _server = _server || web.httpsServer || this;
+
+ switch (typeof handlers) {
+ /**
+ * web.err({ ... });
+ */
+ case 'object':
+ for(var key in handlers) {
+ this.error(key, handlers[key]);
+ }
+ break;
+ /**
+ * web.err(404, function (req, res) { ... });
+ */
+ case 'string':
+ case 'number':
+ if (_server.handlers.error === undefined) {
+ _server.handlers.error = {};
+ }
+ _server.handlers.error[handlers] = server;
+ }
+ return this;
+ };
+ web.err = web.error;
+
+ web.stack = [];
+ if (web.isServer) web._use = web.use;
+ web.use = function () {
+ var _server = this.server || this.httpsServer || this;
+ if (!this.isServer) this._use = _server.use;
+ for (var i = 0; i < arguments.length; i++) {
+ switch (typeof arguments[i]) {
+ case "string":
+ var route = arguments[i];
+ i++;
+ var handle = arguments[i];
+ this._use.call(_server, route, handle);
+ break;
+ case "function":
+ case "object":
+ this._use.call(_server, arguments[i]);
+ break;
+ }
+ }
+ return this;
+ };
+ /**
+ * Run a HTTP server. 启动HTTP Server的主方法
+ * @param {Object} getpath Set a UrlRouter to the server.(require) 传入的URLRouter*
+ * @param {Number} port Port to listen.(require) 监听的端口*
+ * @param {String} host Domain to listen.(require) 监听的域名*
+ *
+ * web.run(8888, 'mydomain.com');
+ *
+ */
+ web.run = function (port, host) {
+ port = port || 80;
+ host = host || '127.0.0.1';
+ var server = connect.createServer();
+ server.setRouter = false;
+ server.self = server.listen(port, host);
+ this.server = server;
+ server.handlers = {};
+ server.rules = {};
+ this.emit('listening', port, host);
+ return this;
+ };
+ /*
+ * @description Run a HTTPS server. 启动HTTP Server的主方法
+ * @param {Object} getpath Set a UrlRouter to the server.(require) 传入的URLRouter*
+ * @param {Number} port Port to listen.(require) 监听的端口*
+ * @param {String} host Domain to listen.(require) 监听的域名*
+ */
+ web.runHttps = function (opt, port, host) {
+ port = port || 80;
+ host = host || '127.0.0.1';
+ var server = connect.createServer();
+ var httpsServer = https.createServer(opt, server);
+ server.setRouter = false;
+ httpsServer.listen(port, host);
+ server.self = httpServer;
+ this.httpsServer = server;
+ server.handlers = {};
+ server.rules = {};
+ this.emit('listening', port, host);
+ return this;
+ };
+ web.fork = function (type, opt) {
+ var _server = this.server || this.httpsServer;
+ _server = _server || this;
+ type = type || 'http';
+ var s = this.create(type, opt);
+ s.handlers = _server.handlers;
+ s.rules = _server.rules;
+ s.metas = _server.metas;
+ return s;
+ };
+
+ web.disable = function (event, handle) {
+ if (handle) {
+ delete this.handlers[event][handle];
+ } else {
+ delete this.handlers.get[handle];
+ }
+ return web;
+ };
+ /*
+ * @description Set the custom 404 page. 设置自定义404页面
+ * @param {String} path 404 page file's name.(require) 需要设置的文件路径(不包括'/')*
+ */
+ web.setErrorPage = function (statu, path) {
+ fs.readFile(path, function (err, data) {
+ web.ErrorPage[statu] = data;
+ });
+ return this;
+ };
+ web.ErrorPage = {};
+ /*
+ * @description 自定义MIME类型
+ * @param {String} format 文件格式后缀*
+ * @param {String} mime MIME类型*
+ */
+ web.extend = function (file) {
+ if (arguments.length = 1)
+ switch (typeof file) {
+ case "string":
+ var extend = require(file);
+ extend(this);
+ break;
+ case "object":
+ var ext = file.ext || file.extend;
+ ext(this);
+ break;
+ case "function":
+ file(this);
+ break;
+ }
+ else
+ for (var i = 0; i < arguments.length; i++) {
+ switch (typeof arguments[i]) {
+ case "string":
+ var extend = require(arguments[i]);
+ extend(this);
+ break;
+ case "object":
+ var ext = arguments[i].ext || arguments[i].extend;
+ ext(this);
+ break;
+ case "function":
+ arguments[i](this);
+ break;
+ }
+ };
+ return this;
+ };
+
+ web.ext = function (name, handle) {
+ web.__defineGetter__(name, function () {
+ return handle
+ });
+ };
+ /*
+ * @description 设置一些需要用到的元数据
+ * @param {String} key 元数据的Key*
+ * @param {String} value 元数据的值*
+ */
+ web.metas = {};
+ web.config = function (key, value) {
+ var self = this;
+ switch (typeof key) {
+ case 'string':
+ if (value !== undefined) {
+ switch (key) {
+ case 'template':
+ web.render = function (tmlp, view, callback) {
+ if (web.set('views') === undefined) tmlp = web.set('views') + '/' + tmlp;
+ var engine = web.set('view engine') || require('jade');
+ fs.readFile(tmlp, function (err, data) {
+ engine.render(data, view, callback);
+ });
+ };
+ break;
+ case 'mode':
+ switch (value) {
+ case 'production':
+ case 'pro':
+ setInterval(function () {
+ web.restart();
+ }, 31536000);
+ web.metas[key] = value;
+ break;
+ case 'development':
+ case 'dev':
+ web.use(web.logger('dev'));
+ global.web.metas[key] = value;
+ break;
+ }
+ break;
+ default:
+ self.metas[key] = value;
+ global.web.metas[key] = value;
+ self.emit('set', key, value);
+ self.emit('config', key, value);
+ global.web.emit('set', key, value);
+ global.web.emit('config', key, value);
+ }
+ } else {
+ if (self.metas[key])
+ return self.metas[key]
+ else
+ return global.web.metas[key];
+ }
+ break;
+ case 'object':
+ for (var meta in key) {
+ self.metas[key] = value;
+ global.web.set(meta, key[meta]);
+ }
+ break;
+ }
+ return this;
+ };
+ web.set = web.config;
+ web.meta = web.set;
+ /*
+ * @description 重启服务器
+ * @param {Object} server 服务器
+ */
+ web.restart = function (server) {
+ if (server) {
+ server.self.close();
+ server.self.listen(server.port, server.host);
+ } else {
+ web.server.self.close();
+ web.server.self.listen(web.server.port, web.server.host);
+ }
+ return this;
+ };
+ /*
+ * @description 停止服务器
+ * @param {Object} server 服务器
+ */
+ web.stop = function(server){
+ server = server ? server : web.server;
+ if(server.fd)
+ server.self.close();
+ return this;
+ };
+ /*
+ * @description 生成一个服务器
+ * @param {String} type 服务器的类型*
+ * @param {Object} opt HTTPS服务器的SSL设置
+ */
+ web.create = function (type, opt) {
+ switch (type) {
+ case 'http':
+ var server = connect.createServer();
+ web.server = server;
+ global.server = server;
+ server.isServer = true;
+ exports.ext(server);
+ return server;
+ break;
+ case 'https':
+ var server = connect.createServer();
+ var httpsServer = https.createServer(opt, server);
+ server.setRouter = false;
+ server.on('listening', function (port, host) {
+ httpsServer.listen(port, host);
+ server.self = httpServer;
+ });
+ web.httpsServer = server;
+ global.httpsServer = server;
+ server.isServer = true;
+ exports.ext(server);
+ return server;
+ break;
+ default:
+ var server = connect.createServer();
+ web.server = server;
+ global.server = server;
+ server.isServer = true;
+ exports.ext(server);
+ return server;
+ }
+ };
+ web.dynamicHelpers = function (obj) {
+ var self = this;
+ return self.use(function (req, res, next) {
+ var dynamicView = {};
+ for (var key in obj) dynamicView[key] = obj[key](req, res);
+ res.dynamicView = dynamicView;
+ self.set('dynamicView', dynamicView);
+ next();
+ });
+ };
+ web.ext = function (name, handle) {
+ web.__defineGetter__(name, function () {
+ return handle
+ });
+ };
+ /*
+ * @description 设置一些需要用到的元数据
+ * @param {String} key 元数据的Key*
+ * @param {String} value 元数据的值*
+ */
+ web.metas = {};
+ web.config = function (key, value) {
+ var self = this;
+ switch (typeof key) {
+ case 'string':
+ if (value !== undefined) {
+ switch (key) {
+ case 'template':
+ web.render = function (tmlp, view, callback) {
+ if (web.set('views') === undefined) tmlp = web.set('views') + '/' + tmlp;
+ var engine = web.set('view engine') || require('jade');
+ fs.readFile(tmlp, function (err, data) {
+ engine.render(data, view, callback);
+ });
+ };
+ break;
+ case 'mode':
+ switch (value) {
+ case 'production':
+ case 'pro':
+ setInterval(function () {
+ web.restart();
+ }, 31536000);
+ web.metas[key] = value;
+ break;
+ case 'development':
+ case 'dev':
+ web.use(web.logger('dev'));
+ global.web.metas[key] = value;
+ break;
+ }
+ break;
+ default:
+ self.metas[key] = value;
+ global.web.metas[key] = value;
+ self.emit('set', key, value);
+ self.emit('config', key, value);
+ global.web.emit('set', key, value);
+ global.web.emit('config', key, value);
+ }
+ } else {
+ if (self.metas[key])
+ return self.metas[key]
+ else
+ return global.web.metas[key];
+ }
+ break;
+ case 'object':
+ for (var meta in key) {
+ self.metas[key] = value;
+ global.web.set(meta, key[meta]);
+ }
+ break;
+ }
+ return this;
+ };
+ web.set = web.config;
+ web.meta = web.set;
+ /*
+ * @description 重启服务器
+ * @param {Object} server 服务器
+ */
+ web.restart = function (server) {
+ if (server) {
+ server.self.close();
+ server.self.listen(server.port, server.host);
+ } else {
+ web.server.self.close();
+ web.server.self.listen(web.server.port, web.server.host);
+ }
+ return this;
+ };
+ /*
+ * @description 停止服务器
+ * @param {Object} server 服务器
+ */
+ web.stop = function(server){
+ server = server ? server : web.server;
+ if(server.fd)
+ server.self.close();
+ return this;
+ };
+ /*
+ * @description 生成一个服务器
+ * @param {String} type 服务器的类型*
+ * @param {Object} opt HTTPS服务器的SSL设置
+ */
+ web.create = function (type, opt) {
+ switch (type) {
+ case 'http':
+ var server = connect.createServer();
+ web.server = server;
+ global.server = server;
+ server.isServer = true;
+ exports.ext(server);
+ return server;
+ break;
+ case 'https':
+ var server = connect.createServer();
+ var httpsServer = https.createServer(opt, server);
+ server.setRouter = false;
+ server.on('listening', function (port, host) {
+ httpsServer.listen(port, host);
+ server.self = httpServer;
+ });
+ web.httpsServer = server;
+ global.httpsServer = server;
+ server.isServer = true;
+ exports.ext(server);
+ return server;
+ break;
+ default:
+ var server = connect.createServer();
+ web.server = server;
+ global.server = server;
+ server.isServer = true;
+ exports.ext(server);
+ return server;
+ }
+ };
+
+ web.render = function () {
+ var self = this;
+ var name = arguments[0];
+ var view = arguments[arguments.length - 2];
+ var callback = arguments[arguments.length - 1];
+ var layout_view = {
+ title: 'webjs starting'
+ };
+ if (view.local) {
+ layout_view = view;
+ view = view.local;
+ }
+ var dynamicHelpers = this.set('dynamicHelpers');
+ for (var key in dynamicHelpers) view[key] = dynamicHelpers[key];
+ var opt = (arguments.length > 2 ? arguments[1] : {});
+ var ext = self.set('view engine') || 'jade';
+ var engine = require(ext);
+ var root = self.set('views');
+ var render = new eventproxy();
+ if (!/\/$/i.test(root)) root += '/';
+ render.assign('layout', 'body', function (layout, body) {
+ layout_view.body = body;
+ engine.render(layout, layout_view, function (err, fin) {
+ if (err) return callback(err);
+ callback(null, fin);
+ });
+ });
+ if (opt.layout !== false) {
+ if (opt.layout === undefined || opt.layout === true) {
+ fs.readFile(root + 'layout.' + ext, function (err, layout) {
+ if (err) return render.trigger('layout', '#{body}');
+ render.trigger('layout', layout.toString());
+ });
+ } else {
+ fs.readFile(root + opt.layout + '.' + ext, function (err, layout) {
+ if (err) return render.trigger('layout', '#{body}');
+ render.trigger('layout', layout.toString());
+ });
+ }
+ } else {
+ render.trigger('layout', '#{body}');
+ }
+ view.partial = function (tmlp) {
+ return fs.readFileSync(root + tmlp + '.' + ext);
+ };
+ fs.readFile(root + name + '.' + ext, function (err, tmlp) {
+ if (err) return self.sendError(500);
+ engine.render(tmlp.toString(), view, function (err, body) {
+ if (err) return self.sendError(500);
+ render.trigger('body', body);
+ });
+ });
+ };
+ web.net = require('./net');
+
+ //Middlewares
+ fs.readdirSync(__dirname + '/middlewares').forEach(function(filename){
+ if (!/\.js$/.test(filename)) return;
+ var name = pathmo.basename(filename, '.js');
+ function load(){ return require('./middlewares/' + name); }
+ web.__defineGetter__(name, load);
+ });
+ for (var i = 0; i < middlewares.length; i++) {
+ web[middlewares[i]] = connect[middlewares[i]];
+ }
+}
+module.exports.ext = method;
53 lib/middlewares/compiler.js
@@ -0,0 +1,53 @@
+/*!
+ * webjs - Compiler
+ * Copyright(c) 2012 C61 Lab
+ * MIT Licensed
+ */
+
+var dataStream = require('dataStream');
+var path = require('path');
+
+module.exports = function (opt) {
+ return function (req, res, next) {
+ if (opt.enable.indexOf(path.extname(req.url).substr(1)) !== -1) {
+ // header fields
+ res.on('header', function () {
+ res.removeHeader('Content-Length');
+ res.setHeader('Content-Type', 'text/css');
+ });
+
+ // pipelining
+ res.on('pipelining', function () {
+ // fetch the render
+ var engine = require(path.extname(req.url).substr(1));
+ var render = engine.render || engine.compile;
+
+ // create the stream
+ var stream = new dataStream({ readable: false });
+
+ // fetch the static root
+ var root = global.web.set('static root');
+
+ // listening
+ stream.on('complete', function () {
+ // file body
+ var body = stream.body().toString();
+
+ // empty the stream
+ stream.empty();
+
+ // rende it
+ render(body, { paths: [root, root + '/css'] }, function (err, css) {
+ if (err) return stream.emit('data', body);
+ stream.emit('data', css);
+ });
+
+ });
+
+ // return the stream to pipeling
+ return stream;
+ });
+ }
+ next();
+ };
+};
129 lib/middlewares/compress.js
@@ -0,0 +1,129 @@
+
+/*!
+ * Connect - compress
+ * Copyright(c) 2010 Sencha Inc.
+ * Copyright(c) 2011 TJ Holowaychuk
+ * Copyright(c) 2012 Will Wen Gunn
+ * MIT Licensed
+ */
+
+/**
+ * Module dependencies.
+ */
+
+var zlib = require('zlib');
+var ext = require('path').extname;
+var mime = require('mime');
+
+/**
+ * Supported content-encoding methods.
+ */
+
+exports.methods = {
+ gzip: zlib.createGzip,
+ deflate: zlib.createDeflate
+};
+
+/**
+ * Default filter function.
+ */
+
+exports.filter = function(req, res){
+ var url = req.url;
+ var extname = res.extname;
+
+ // index.html support
+ if ('/' == url[url.length - 1]) url += 'index.html';
+
+ // Lookup the file mime type
+ var type = mime.lookup(ext(url)) || mime.lookup(extname);
+ type = type || '';
+ return type.match(/json|text|javascript|less|scss|sass|coffeescript/);
+};
+
+/**
+ * Compress:
+ *
+ * Compress response data with gzip/deflate.
+ *
+ * Filter:
+ *
+ * A `filter` callback function may be passed to
+ * replace the default logic of:
+ *
+ * exports.filter = function(req, res){
+ * var type = res.getHeader('Content-Type') || '';
+ * return type.match(/json|text|javascript/);
+ * };
+ *
+ * Options:
+ *
+ * All remaining options are passed to the gzip/deflate
+ * creation functions. Consult node's docs for additional details.
+ *
+ * - `chunkSize` (default: 16*1024)
+ * - `windowBits`
+ * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression
+ * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more
+ * - `strategy`: compression strategy
+ *
+ * @param {Object} options
+ * @return {Function}
+ * @api public
+ */
+
+module.exports = function compress(options) {
+ var options = options || {};
+ var names = Object.keys(exports.methods)
+ var filter = options.filter || exports.filter;
+
+ return function(req, res, next){
+ var accept = req.headers['accept-encoding'];
+ var write = res.write;
+ var end = res.end;
+ var stream;
+ var method;
+
+ // vary
+ res.setHeader('Vary', 'Accept-Encoding');
+
+ // default request filter
+ if (!filter(req, res)) return next();
+
+ // SHOULD use identity
+ if (!accept) return next();
+
+ // head
+ if ('HEAD' == req.method) return next();
+
+ // default to gzip
+ if ('*' == accept.trim()) method = 'gzip';
+
+ // compression method
+ if (!method) {
+ for (var i = 0, len = names.length; i < len; ++i) {
+ if (~accept.indexOf(names[i])) {
+ method = names[i];
+ break;
+ }
+ }
+ }
+
+ // compression method
+ if (!method) return next();
+
+ // compression stream
+ stream = exports.methods[method](options);
+
+ // header fields
+ res.on('header', function () {
+ res.setHeader('Content-Encoding', method);
+ res.removeHeader('Content-Length');
+ });
+ res.on('pipelining', function () {
+ return stream;
+ });
+
+ next();
+ };
+}
16 lib/middlewares/patch.js
@@ -0,0 +1,16 @@
+/*!
+ * webjs - Request and Response Patch
+ * Copyright(c) 2012 C61 Lab
+ * MIT Licensed
+ */
+
+var Request = require('../request');
+var Response = require('../response');
+
+module.exports = function () {
+ return function (req, res, next) {
+ req = new Request(req);
+ res = new Response(res);
+ next();
+ }
+};
54 lib/middlewares/router.js
@@ -0,0 +1,54 @@
+
+/*!
+ * webjs - Router
+ * Copyright(c) 2011 C61 Lab
+ * MIT Licensed
+ */
+
+var Request = require('../request');
+var Response = require('../response');
+var utils = require('../utils');
+var url = require('url');
+
+module.exports = function (_req, _res, out) {
+ var server = global.web.server;
+ var handlers = server.handlers;
+ var rules = server.rules;
+ var errorHandler = (handlers.error ? handlers.error[0] : null);
+
+ global.web.emit(_req.method.toLowerCase(), _req, _res);
+ var hit = null;
+ var _rule = null;
+
+ for (var key in rules[_req.method.toLowerCase()]) {
+ if (rules[_req.method.toLowerCase()][key].test(url.parse(_req.url).pathname)) {
+ hit = handlers[_req.method.toLowerCase()][key];
+ _rule = { key: key, rule: rules[_req.method.toLowerCase()][key] };
+ break;
+ }
+ }
+
+ if (hit) {
+ var req = new Request(_req);
+ var res = new Response(_res, _req);
+ } else {
+ return out();
+ }
+ try {
+ req.params = utils.restParser(_rule.key, _rule.rule, req.reqPath);
+ if (errorHandler) {
+ hit(req, res, function (err) {
+ errorHandler(err, req, res, out);
+ });
+ } else {
+ hit(req, res, out);
+ }
+ } catch (e) {
+ if (errorHandler) {
+ errorHandler(e, req, res, out);
+ } else {
+ out(e);
+ }
+ }
+
+}
262 lib/middlewares/static.js
@@ -0,0 +1,262 @@
+/*!
+ * Connect - staticProvider
+ * Copyright(c) 2010 Sencha Inc.
+ * Copyright(c) 2011 TJ Holowaychuk
+ * Copyright(c) 2012 Will Wen Gunn
+ * MIT Licensed
+ */
+
+/**
+ * Module dependencies.
+ */
+
+var fs = require('fs');