I am starting a new Node.js app and this time, I'm trying to organize the code correctly instead of having everything in the same file.
I only have a simple setup now at server.coffee
:
express = require 'express'
app = module.exports = express.createServer()
## CONFIGURATION ##
app.configure () ->
app.set 'views', __dirname + '/views'
app.set 'view engine', 'jade'
app.use express.bodyParser()
app.use express.logger('dev')
app.use express.profiler()
app.use express.methodOverride()
app.use app.router
app.use express.static(__dirname + '/public')
app.configure 'development', () ->
app.use express.errorHandler({dumpExceptions: true, showStack: true})
app.configure 'production', () ->
app.use express.errorHandler()
app.get '/', (req,res) ->
res.render 'index'
title: 'Express'
## SERVER ##
port = process.env.PORT || 3000
app.listen port, () ->
console.log "Listening on port" + port
I have some questions regarding that simple code and I know that all the answers depend on the developer but I really want to do it right:
- Should the
server.js
file have more than theapp.listen
? What should be there exactly? - Shouldn't all the configurations be in a different file than the routes? How can I remove the
app.get
to other file and make them work when I run theserver.coffee
? - What exactly should contain the
index.coffee
that I see in a lot of apps like Hubot?
I hope someone can give me an answer other than "it depends".
There are 2 similar question that can help you a lot with this:
How to structure a express.js application?
Nodejs/Expressjs app structure
You can leverage
require
, and simply pass theapp
var in as a parameter to a method. It's not the prettiest syntax, nor is it in CoffeeScript, but you should get the idea.routes.js
app.js
If you want to take it a step further, I separate my routes into smaller groups, and in it's own subfolder. (like:
routes/auth.js
for login/logout,routes/main.js
for home/about/contact and so on)routes/index.js
(rename
routes.js
from before asroutes/main.js
, the source itself remains the same)Express 4 simplifies this with the
express.Router
class.