zw0kag
Last Updated: February 25, 2016
·
635
· dylanlukes

Hot CoffeeScript Express Boilerplate

Tired of extra syntax in your Express app.js, or want to switch to CoffeeScript for your server-side code? Try this pseudo-DSL on for size:

run.js

coffee = require('coffee-script');
http   = require('http');
app    = require('./app');

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

app.coffee

express = require 'express'
_       = require 'underscore'
path    = require 'path'

routes = require './routes'
user   = require './routes/user'

module.exports = app = express()

do _.bind ->
    @configure ->
      @set('port', process.env.PORT || 3000)
      @set('views', __dirname + '/views')
      @set('view engine', 'jade')
      @use(express.favicon())
      @use(express.logger('dev'))
      @use(express.bodyParser())
      @use(express.methodOverride())
      @use(@router)
      @use(express.static(path.join(__dirname, 'public')))

    @configure 'development', ->
      @use(express.errorHandler())

    @get('/', routes.index)
    @get('/users', user.list)
  , app

Watch out for the indentation. The second argument to bindexpress() – is indented once, but the contents of the function are indented twice.

1 Response
Add your response

11549

In coffeescript you can use do => (fat arrow http://coffeescript.org/#fat-arrow) to automatically perform the binding.

over 1 year ago ·