Permalink
Browse files

v0.5.8 Added United Test and fixed some bugs

  • Loading branch information...
1 parent 20bb3d7 commit 5d592f2497452c5496d27db91eaa9706759cfbff @iwillwen committed Aug 3, 2012
View
196 README.md
@@ -20,27 +20,27 @@ or
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首页。
+ '/: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');
+ '/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));
- }
+ '/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
+ .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 简单化部署
@@ -67,11 +67,11 @@ Yes! It's so cool!
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
+ '/: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);
+ .url(urlRouter);
# HTTP Mothod HTTP方法
@@ -80,34 +80,34 @@ Yes! It's so cool!
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对象,不需要'./'
- }
+ '/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方法规则
+ .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 + '!');
- }
+ '/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());
+ web.run(8888)
+ .post(postRouter) //Set the post router. 传入POST方法规则
+ .use(web.bodyParser());
## 其他HTTP方法
@@ -117,14 +117,14 @@ 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 + '!');
- }
+ '/putHello' : function (req, res) {
+ res.send('Hello ' + req.data.name + '!');
+ }
};
web.run(8888)
- .put(postRouter)
- .use(web.bodyParser());
+ .put(postRouter)
+ .use(web.bodyParser());
## HTTPS
@@ -135,29 +135,29 @@ HTTPS方法与HTTP方法相同
var web = require('webjs');
var urlRouter = {
- '/:id.html' : 'page.html',
- '/google' : 'http://www.google.com'
+ '/: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);
- }
+ '/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 + '!');
- }
+ '/postHello' : function (req, res) {
+ res.send('Hello ' + req.data.name + '!');
+ }
};
web.runHttps(8888)
- .url(urlRouter)
- .get(getRouter)
- .post(postRouter);
+ .url(urlRouter)
+ .get(getRouter)
+ .post(postRouter);
## Response Pipelining
@@ -167,29 +167,29 @@ You can use this to edit the data will be sent to the client. Such as compress,
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();
+ .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
@@ -205,14 +205,14 @@ Web.js supports the middleware.
var web = require('webjs');
web.run()
- .use(
- web.bodyParser(),
- web.cookiesParser('webjs'),
- web.session(),
- web.compress(),
- web.complier({ enable: ["less", "sass"] }),
- web.static(__dirname + '/static')
- );
+ .use(
+ web.bodyParser(),
+ web.cookieParser('webjs'),
+ web.session(),
+ web.compress(),
+ web.complier({ enable: ["less", "sass"] }),
+ web.static(__dirname + '/static')
+ );
# webjs plugin
@@ -225,25 +225,25 @@ You can use it to modular your app functions.
module.exports = function (web) {
- web.get({
- '/some': function (req, res) {
- res.send('some');
- }
- });
+ 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
- });
+ web.__defineGetter__('foo', function () {
+ return this.servers;
+ });
+
+ // or
+ web.fn('bar', funtion () {
+ // do something
+ });
}
View
480 bin/webjs 100755 → 100644
@@ -8,93 +8,93 @@ 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('');
- });
+ .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));
- });
+ .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();
+ .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';
@@ -103,193 +103,193 @@ 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>'
+ '<!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;',
- '}'
+ '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);',
- '}'
+ '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!\');'
+ '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\'',
- ' });',
- ' });',
- '};'
+ '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/\');'
+ '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' : '')
+ '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'
+ '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);
+ 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();
+ 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();
+ if (err) throw err;
+ console.log(' \033[36mcreate\033[0m : ' + path);
+ fn && fn();
});
}
function list (val) {
- return val.split(',');
+ return val.split(',');
}
View
25 examples/play.js
@@ -1,13 +1,13 @@
-var http = require('http'),
- asynclist = require('asynclist');
+var http = require('http');
+var asynclist = require('asynclist');
var opts = {
host: '127.0.0.1'
};
-var list = [],
- succeed = 0,
- failed = 0;
-for (var i = 0; i < 1001; i++)
+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 () {
@@ -20,12 +20,13 @@ for (var i = 0; i < 1001; i++)
tasks.trigger(false);
});
});
-var timeout = 0,
- timer = setInterval(function () {
- timeout++;
- }, 1);
+}
+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');
+ clearInterval(timer);
+ console.log('Finished. Used time: ' + timeout + 'ms');
}).run();
View
90 examples/reponsePipeling.js
@@ -4,63 +4,61 @@ var web = require('webjs');
var dataStream = require('dataStream');
web.run(8888)
- .use(web.cookieParser('webjs'))
- .use(web.session())
+ .use(web.cookieParser('webjs'))
+ .use(web.session())
- // Response Pipelining
- .use(web.complier({ enable: ["less"] }))
- .use(function (req, res, next) {
+ // Response Pipelining
+ .use(web.complier({ enable: ["less"] }))
+ .use(function (req, res, next) {
- var render = function (body) {
- // do something
- };
- var complieStream = new dataStream({ readable: false });
+ var render = function (body) {
+ // do something
+ };
+ var complieStream = new dataStream({ readable: false });
- complieStream.on('complete', function () {
- var body = this.body()/* Buffer */
- .toString();
+ complieStream.on('complete', function () {
+ var body = this.body()/* Buffer */
+ .toString();
- // empty the stream
- this.empty();
+ // empty the stream
+ this.empty();
- // pipe data to the next stream
- this.emit('data', render(body));
- });
+ // pipe data to the next stream
+ this.emit('data', render(body));
+ });
- res.pipelining(function () {
- return complieStream;
- });
+ res.pipelining(function () {
+ return complieStream;
+ });
- next();
- })
- .use(web.compress())
- .use(function (req, res, next) {
+ next();
+ })
+ .use(web.compress())
+ .use(function (req, res, next) {
- // collect data
+ // collect data
- res.__defineGetter__('data', function () {
- return function (data) {
- this.data = data;
- }
- })
+ res.data = function (data) {
+ this.data = data;
+ }
- // Working
- res.pipelining(function () {
- switch (this.data.type) {
- case "one":
- // do something
- }
- });
+ // Working
+ res.on('pipelining', function () {
+ switch (this.data.type) {
+ case "one":
+ // do something
+ }
+ });
- next();
- })
- .use(web.static(__dirname + '/../static'));
+ next();
+ })
+ .use(web.static(__dirname + '/../static'));
- /**
- *
- * Pipeline
- * Static -> Complier -> Custom Complier -> Compress -> Data Mining -> Response
- *
- */
+ /**
+ *
+ * Pipeline
+ * Static -> Complier -> Custom Complier -> Compress -> Data Mining -> Response
+ *
+ */
console.log('The app is running!');
View
23 examples/sayhello-sex.js
@@ -1,16 +1,17 @@
var web = require('webjs');
var getRouter = {
- 'name\/(.*)': function (req, res) {
- switch (qs.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.');
- }
- }
+ '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)
- .get(getRouter);
+ .use(web.query())
+ .get(getRouter);
View
52 examples/sayhello.js
@@ -2,44 +2,44 @@ 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'
+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.on('response',function(res){
- res.on('data',function(chunk){
- console.log('body:' + chunk);
- })
- });
- req.end();
+ });
+ req.end();
}
var getRouter = {
- 'name\/(.*)': function (req, res) {
- res.send('Hey! Mr. ' + decodeURI(req.path[0]) + '! Nice to meet you.');
- },
- 'getQuerystring' : function (req, res) {
- res.sendJSON('querystring');
- }
+ '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.get(getRouter);
- ask();
-},3000);
+setTimeout(function () {
+ web.use(web.query)
+ .get(getRouter);
+ ask();
+}, 3000);
var util = require('util'),
- spawn = require('child_process').spawn,
- ls = spawn('ls', ['-lh', '/usr']);
+ spawn = require('child_process').spawn,
+ ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
View
22 examples/webjsoncoffee.coffee
@@ -2,20 +2,20 @@ web = require 'webjs'
web.run(8888)
.config(
- 'views': __dirname + '/../views'
- 'view engine': 'jade'
- 'mode': 'dev'
+ 'views': __dirname + '/../views'
+ 'view engine': 'jade'
+ 'mode': 'dev'
)
.use(
- web.complier enable: ["less"]
- do web.compress
- '/public', web.static __dirname + '/..'
- )
+ 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!'
+ '/hello': (req, res) ->
+ res.send 'Hello Green World!'
+ '/sayName': (req, res) ->
+ res.send 'I\'m the World!'
console.log 'The app is runing!'
View
2 index.js
@@ -1,7 +1,7 @@
/*
* @fileOverview
* @author Will Wen Gunn
- * @version 0.5.7
+ * @version 0.5.8
*/
/*
* @constructor webjs
View
70 lib/httpstatus.js
@@ -1,37 +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'
+ '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'
};
View
4 lib/index.js
@@ -6,8 +6,8 @@ require('./method').ext(web);
require('emitter')(web);
global.__defineGetter__('web', function () {
- return web;
+ return web;
});
global.__defineSetter__('web', function (_web) {
- web = _web;
+ web = _web;
});
View
1,055 lib/method.js
@@ -1,4 +1,3 @@
-
//Modules
var fs = require("fs");
var pathmo = require('path');
@@ -15,553 +14,557 @@ 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.7';
+ //Method
+ web.version = '0.5.8';
- /**
- * 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, next) {
- var tasks = new asynclist(fn1);
- tasks.assign(function () {
- fn2(req, res, next)
- }).run(req, res, function () {
- if (arguments[0] instanceof Error) return res.render('error/error', {
- title: arguments[0].message,
- root: __dirname,
- layout: false,
- local: {
- title: arguments[0].message,
- message: arguments[0].message,
- stack: arguments[0].stack
- }
- });
- tasks.trigger(true);
- });
- }
- };
- /**
- * 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;
+ /**
+ * 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, next) {
+ var tasks = new asynclist(fn1);
+ tasks.assign(function () {
+ fn2(req, res, next)
+ }).run(req, res, function () {
+ if (arguments[0] instanceof Error) return res.render('error/error', {
+ title: arguments[0].message,
+ root: __dirname,
+ layout: false,
+ local: {
+ title: arguments[0].message,
+ message: arguments[0].message,
+ stack: arguments[0].stack
+ }
+ });
+ tasks.trigger(true);
+ });
+ }
+ };
+ /**
+ * 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;
+ //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]);
}
- 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;
- }
+ break;
+ /**
+ * web.get('/hello', function (req, res) { ... });
+ */
+ case 'string':
+ if (_server.handlers[method] === undefined && _server.handlers[method] === undefined) {
+ _server.handlers[method] = {};
+ _server.rules[method] = {};
}
- 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) {
- var handler = arguments[arguments.lenght - 1];
- if (arguments.lenght > 2) var middlewaves = arguments[1];
- if (middlewaves) {
- return this.httpMethodHelper(method, web._(middlewaves, handler));
+ _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 {
- return this.httpMethodHelper(method, handler);
+ _server.rules[method][handlers] = /^([\/\w$%.-]*)$/i;
}
- };
- /**
- * 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);
+ }
+ 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);
}
- };
- /**
- * 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);
+ }
+ }
+ return this.httpMethodHelper('get', _urlhandlers, server);
+ };
+ /*
+ * @description 设置GET和POST响应错误时的错误响应
+ * @param {Object} handlers 传入的ErorrHandlers*
+ */
+ web.error = function (handlers, server) {
+ return this.httpMethodHelper('error', handlers, server);
+ };
+ 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;
}
- };
- /**
- * 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));
+ };
+ 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 {
- return this.httpMethodHelper('put', _puthandlers, server);
+ if (self.metas[key])
+ return self.metas[key]
+ else
+ return global.web.metas[key];
}
- };
-
- 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) {
- return this.httpMethodHelper('error', handlers, server);
- };
- web.err = web.error;
-
- 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;
- }
+ break;
+ case 'object':
+ for (var meta in key) {
+ self.metas[key] = value;
+ global.web.set(meta, key[meta]);
}
- 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';
+ 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();
- server.setRouter = false;
- server.self = server.listen(port, host);
- this.server = server;
- server.handlers = {};
- server.rules = {};
- 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';
+ 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;
- httpsServer.listen(port, host);
- server.self = httpServer;
- this.httpsServer = server;
- server.handlers = {};
- server.rules = {};
- 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;
+ server.on('listening', function (port, host) {
+ httpsServer.listen(port, host);
+ server.self = httpServer;
});
- 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.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.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;
-