Dinamically import all models/controllers in Express
I have been playing with Express 3 for quite some time now, and one of the first challenges I had was to make it "look" more like Rails in terms of convention. I was quite frustrated to see so many Node projects storing the whole application logic in one file, just because Express allows for it.
So, I came up with a solution so that you can have "models" and "controllers" in separate files and folders (in CoffeeScript):
fs = require 'fs'
models_path = "#{__dirname}/models"
fs.readdir models_path, (err, files) ->
files.forEach (file) -> require "#{models_path}/#{file}"
Same applies for controllers just by changing the path, don't forget to "export"(module.exports= {}) all your code, so that is accessible throughout the application.
Let me know what you think.
Written by Caio Bianchi
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#