Skip to content

Instantly share code, notes, and snippets.

@dylants
Last active December 23, 2015 22:49
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 dylants/6705338 to your computer and use it in GitHub Desktop.
Save dylants/6705338 to your computer and use it in GitHub Desktop.
Node Express app.js (generic)
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