Skip to content

Instantly share code, notes, and snippets.

@krasimir
Created November 30, 2012 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krasimir/4178295 to your computer and use it in GitHub Desktop.
Save krasimir/4178295 to your computer and use it in GitHub Desktop.
Organization of Expressjs type of node apps
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