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, loadWritten by Matthew Hudson
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Coffeescript
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#