Created
November 30, 2012 20:15
-
-
Save krasimir/4178295 to your computer and use it in GitHub Desktop.
Organization of Expressjs type of node apps
This file contains 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 mode = process.argv[2] ? process.argv[2] : "local"; | |
mode = mode.replace("/", "") == "tests" ? "local" : mode; | |
var express = require('express'); | |
var app = express(); | |
var config = require("./config/" + mode).config; | |
var glob = require("glob"); | |
var path = require('path'); | |
// helper middlewares | |
var attach = function(req, res, next) { | |
// attach something needed to req | |
next(); | |
} | |
var init = function() { | |
var root = __dirname; | |
glob(root + "/actions/**/*.js", function (err, files) { | |
files.reverse(); | |
for(var i in files) { | |
var action = require(files[i]).action; | |
if(action) { | |
var route = path.dirname(files[i]); | |
route = route.replace(root, "").replace("/actions", ""); | |
if(path.basename(files[i]) != "index.js") { | |
route += "/" + path.basename(files[i]).replace(".js", ""); | |
} | |
route = route == "" ? "*" : route; | |
console.log("route (" + (action.method || "all") + ") > " + route + " (" + files[i] + ")"); | |
app[action.method || "all"](route, [attach, currentUser, action.handler]); | |
} | |
} | |
}); | |
app.use(express.bodyParser()); | |
app.listen(config.port); | |
console.log('listening on port ' + config.port); | |
} | |
exports.app = app; | |
exports.init = init; | |
init(); | |
/* | |
Example of action: | |
exports.action = { | |
handler: function(req, res, next) { | |
res.json(200, {}); | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment