0

I am writing a server side application with nodejs. I am new to this platform so please bear with me. Firstly my application structure :

enter image description here

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)

Sikorski
  • 2,653
  • 3
  • 25
  • 46
  • 2
    possible duplicate of [How to make the require in node.js to be always relative to the root folder of the project?](http://stackoverflow.com/questions/10860244/how-to-make-the-require-in-node-js-to-be-always-relative-to-the-root-folder-of-t) – DrakaSAN Sep 25 '14 at 12:58
  • well the linked question does give me options to avoid ../../.. problem , but can someone comment on my approach ! – Sikorski Sep 25 '14 at 14:31

0 Answers0