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
Written by Matthew Hudson
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Coffeescript
Authors
iam4x
94.17K
ericdfields
63.02K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#