hamkya
Last Updated: February 25, 2016
·
428
· matthewhudson
2013 07 30 19.16.09

Auto-loading express middleware, coffee-style

I like each of my middleware functions to be in separate files, and consolidated into a single directory called, you guessed it, 'middleware'.

I then simply require() my middleware.coffee auto-loader, and all my middleware is automagically loaded:

console.log 'Exporting all custom middleware'

fs        = require 'fs'
path      = require 'path'
basename  = path.basename

exports.middleware = {}

# Auto-load middleware with getters.
fs.readdirSync("#{__dirname}/middleware").forEach (fileName) ->
  load = ->
    require "./middleware/#{moduleName}"
  return  unless /\.coffee$/.test(fileName)

  moduleName = basename(fileName, '.coffee')
  exports.middleware.__defineGetter__ moduleName, load
  exports.__defineGetter__ moduleName, load
Say Thanks
Respond