4

I'm building a larger web app, and have now begun to realise the use of modularising my routes in its own files. But when doing this I notice I have to reapeat alot of requirements... Before i started to move out the routes to its own file I had around 20 required modules in my main app, handling everything from DB to emails...

Many of these modules are used in most of the routes... which mean I have to repeat maybe 15-20 requirements in each route module file.

Question: This seems like a alot of repeated code, but maybe this is the righ way to do it?

At least official NPM modules seems to work in this way.

Anders Östman
  • 3,702
  • 4
  • 26
  • 48
  • I realise now that not only requirements has to be duplicated in many files, but also configuration for modules like DB and others... Am I doing something wrong here? – Anders Östman Aug 21 '14 at 08:16
  • Regards database part: you intialise it once. Even if you `import` database access module many times, in reality it will be imported once, and previously created connection will still be available (granted you made it right way). – alandarev Aug 21 '14 at 08:55

1 Answers1

4

You may write a module (lets say, common.js), which would require all of your requirements and return a single object:

module.exports = {
  http:        require('http'),
  request:     require('request'),
  async:       require('async'),
  someModule:  require('./someModule')
};

Then all you have to do is require a single common module:

var common = require('./common');
common.request.get(...);
common.async.parallel(...);

The only inconvenience is that you now have to write common. when you want to access these modules.

You can also use global variables. Actually using globals is a bad practice, and it's strongly recommended that you don't use them:
Why are global variables considered bad practice? (node.js)
Why are globals bad?

Community
  • 1
  • 1
Oleg
  • 22,300
  • 9
  • 68
  • 84
  • Nice idea! Now I at least know that required modules are cached, and not "processed" multiple times... and that was my biggest concern, rather than the problem of manually writing (copy-paste) these requirements in every file. – Anders Östman Aug 21 '14 at 12:35
  • Yeah, you're right about caching. This is what I forgot to mention about :) – Oleg Aug 21 '14 at 12:40