Troy Goode


npm install require-directory

A common pattern I have found when building node.js applications revolves around how you refactor a large file into a directory of smaller files. For example, in an Express app you might start out defining routes in your app.js file, but eventually migrate those routes into a routes.js file that is then required into app.js. What happens when routes.js grows too large though? You chunk it up. You often end up with a routes/ directory, giving you a project structure that looks something like this:

I also find it common to throw an index.js file into that routes/ directory, which might look like:

module.exports = {
auth: require('./auth'),
home: require('./home'),
products: require('./products')
};
view raw index.js hosted with ❤ by GitHub

Eventually you might find that routes/auth.js has grown too large for one file as well, and you may refactor your files to look more like so:

This changes your routes/index.js file into:

module.exports = {
auth: {
login: require('./auth/login'),
logout: require('./auth/logout'),
register: require('./auth/register')
},
home: require('./home'),
products: require('./products')
};
view raw index2.js hosted with ❤ by GitHub

... and so on and so forth. As node.js applications grow larger I see this pattern repeated over and over, often within the same application. To that end, I created require-directory - an npm package that simplifies that index.js file down into:

module.exports = require('require-directory')(module);
view raw index3.js hosted with ❤ by GitHub

For more information, check out the package's GitHub page.