I have a nodejs project that is getting rather large rather fast. Due to my limited understanding of modules and require I am sure that I can do some things to clean up the code and structure.
<app dir>
-app.js
- <modules>
-module1.js
-module2.js
- <routes>
-route1.js
-route2.js
- <utilties>
-utility1.js
-utility2.js
- <authentication>
-local.js
-basic.js
-index.js
My app.js is pretty messy as I have dependencies between my files. IE I want to pass my models and authentication to my routes, utilities can be used by a bunch of things.
var app = express();
... // do express setup
var authenticationStrategy = // get auth strategy from config
var auth = require('./auth)(authenticationStrategy);
var utility1 = require('./utilities/utility1.js');
var utility2 = require('./utilities/utility2.js');
var utilities = {
utility1: utility1,
utility2: utility2
}
var Model1 = require('./models/model1')(utilities);
var Model2 = require('./models/model2')(utility1);
var models = {
Model1: Model1,
Model2: Model2
}
// Dynamically import all routes
fs.readdirSync('routes').forEach(function(file) {
if (file[0] == '.') return;
var route = file.substr(0, file.indexOf('.'));
require('./routes/' + route)(app, models, utilities);
});
...
etc
I now know that I can put an index.js in each folder to clean things up but that still leaves me with having to save off things like utilities and pass that into other require calls.
I can put each require in lower modules only where its needed but then I end up climbing the directory structure with my require which also seems messy, i.e.:
model1.js: var utility1 = require('../utilities/utility1.js');
Basically I think my problem is that modules in lower level folders depend on other modules in other folders. With I feel like I should pull in all dependencies in app.js and pass them to the require modules that need them.
Any advice. I have been trying to restructure this for a couple days and I just keep banging my head against the wall as nothing I do is really making it any better.
Best would be a good node project layout that uses things like mongoose, express, w/ custom modules. and show a good way to handle interdependencies between modules.