Last active
December 29, 2015 05:39
-
-
Save supersha/7623142 to your computer and use it in GitHub Desktop.
给express的router封装一下,使得可以按照目录指定router,这样之后就可以直接在相应的目录下直接添加文件,就可以访问,而无需关注router的问题。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var routerExpress = require("router-express"), | |
express = require("express"); | |
var app = express(); | |
routerExpress.express(app); | |
routerExpress.add("/restart") | |
.add("/api/*.json", "app/api") | |
.add("/tool/*", "app/tool") | |
.add("/test/*") | |
.add("/"); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var url = require("url"); | |
var expressApp = null; | |
module.exports = { | |
express : function(app){ | |
expressApp = app; | |
return this; | |
}, | |
add : function(router, folderpath /* 指定文件目录[option] */){ | |
var response = function(req, res){ | |
var pathname = url.parse(req.url).pathname.replace(/(\.json)$/,""), | |
filename = "", | |
tmpArr = null; | |
pathname = (pathname === "/") ? "/app/page/index" : pathname; | |
try { | |
if(folderpath){ | |
tmpArr = pathname.split("/"); | |
filename = tmpArr[tmpArr.length - 1]; | |
require("../" + folderpath + "/" + filename).showPage(req, res); | |
}else{ | |
require(".." + pathname).showPage(req, res); | |
} | |
} catch (e) { | |
res.writeHead(500, {"Content-Type": "text/plain"}); | |
res.write(e.message); | |
res.end(); | |
} | |
}; | |
expressApp.get(router, response); | |
expressApp.post(router, response); | |
return this; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//比如这是某个目录下新建的一个文件,只要按照下面的方式,exports一个showPage方法出来,作为主入口函数,并response send。 | |
exports.showPage = function(req,res){ | |
res.send(200, "hello world"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment