Last active
December 23, 2015 22:49
-
-
Save dylants/6705338 to your computer and use it in GitHub Desktop.
Node Express app.js (generic)
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 express = require("express"), | |
fs = require("fs"), | |
cons = require("consolidate"), | |
app = express(); | |
// configure the app (all environments) | |
app.configure(function() { | |
// read the port from the environment, else set to 3000 | |
app.set("port", process.env.PORT || 3000); | |
// configure view rendering (underscore) | |
app.engine("html", cons.underscore); | |
app.set("view engine", "html"); | |
app.set("views", __dirname + "/views"); | |
// use express' body parser to access body elements later | |
app.use(express.bodyParser()); | |
// pull in all the controllers (these contain routes) | |
fs.readdirSync("controllers").forEach(function(controllerName) { | |
require("./controllers/" + controllerName)(app); | |
}); | |
// lock the router to process routes up to this point | |
app.use(app.router); | |
// static assets processed after routes, mapped to /public | |
app.use("/public", express.static(__dirname + "/public")); | |
}); | |
// configuration for development environment | |
app.configure("development", function() { | |
console.log("in development environment"); | |
app.use(express.errorHandler()); | |
}); | |
// configuration for production environment (NODE_ENV=production) | |
app.configure("production", function() { | |
console.log("in production environment"); | |
// configure a generic 500 error message | |
app.use(function(err, req, res, next) { | |
res.send(500, "An error has occurred"); | |
}); | |
}); | |
// start the app | |
app.listen(app.get("port"), function() { | |
console.log("Express server listening on port " + app.get("port")); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment