I am writing a server side application with nodejs. I am new to this platform so please bear with me. Firstly my application structure :
Along with this there is an index.js
in parallel to app directory.
Now if i want to access logger.js
or db.js
from let's say controller.js in foo/bar directory then I have to write require('../../logger.js')
. My concern is that if this directory structure goes on increasing then require
calls will be full of '../../../'
ugly bits. To correct this i thought of export a function from every file which would take all the objects that it requires instead of writing individual require. For eg my /foo/bar/routes.js
function routes(router,logger,controller){
//This is express.router()
router.get('/a/:b', function(req, res, next) {
var b = req.params.b;
controller.getAByB(b,function(error,result){
if(!error){
logger.debug('it is working');
//other processing
}
});
});
}
module.exports.routes = routes;
In similar way i would make other files, one more here for example : /foo/bar/controller.js
module.exports = function(logger,db,config){
return {
getAByB : function(b,cb){
logger.log(b);
cb(undefined,'someting');
},
getName : function(cb){
db.fetch(function(res){
cb(res)
});
}
}
}
Does this makes sense ? Please suggest if you find something more could be useful here. Also will this approach make writing of unit tests harder (just so you know i have never written unit tests in js before)