Last Updated: February 25, 2016
·
1.23K
· caiobianchi

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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
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