# NodeJS Best Practice for require()



## ste2425 (Dec 12, 2013)

Im in the process of splitting my nodeJS 'app.js' file into separate modules for different functionality, Passport in a module, mongodb stuff, API stuff, SQLserver interaction  etc.

Trouble is some of them require the same modules. So passport needs access to Mongo as well as some of the API stuff. Currently each module does its own require for the things it needs then in my app.js just the modules themselves are required and used for my routes. 

The problem is this means im in the situation where I get duplicates of things like mongo required. 

So my question what is best practice in this situation? The alternative I can think of is require any things that could be duplicated, like Mongo, in my app.js and pass that around. But im not a fan on having to pass things around to me the point of putting things into modules is to make it completely self contained and independent of the rest of the programme. Relying on dependencies seems to defeat that.


----------



## Castiel (Dec 12, 2013)

Sadly, I just started learning Node and Mongo so I don't know enough to help you with this. Have you tried to ask this on Stackoverflow? I only suggest this because you may get a quicker answer by asking it there than here.


----------



## ste2425 (Dec 12, 2013)

Castiel said:


> Sadly, I just started learning Node and Mongo so I don't know enough to help you with this. Have you tried to ask this on Stackoverflow? I only suggest this because you may get a quicker answer by asking it there than here.



Ive referenced Stackoverflow allot when i have problems but i don't have an account on there myself, don't know why but always felt a little intimidated at the thought of asking questions myself


----------



## Castiel (Dec 12, 2013)

ste2425 said:


> Ive referenced Stackoverflow allot when i have problems but i don't have an account on there myself, don't know why but always felt a little intimidated at the thought of asking questions myself



I understand. Stackoverlow can have some big a-holes on there at times.


----------



## ste2425 (Dec 12, 2013)

Castiel said:


> I understand. Stackoverlow can have some big a-holes on there at times.



yup, but to be fair just as many people who go into allot of detail explaining their answers.

Im leaning to the idea of having everything self contained within its own module rather then passing an instance of mongo and monk in all over the place. Even if that means calling:


```
var monk = require('monk');
var mongo = require('mongodb');
```

multiple times in different modules.

Plus it means my modules can be reused in other applications without any external dependencies, well as long as mongo etc is installed on the system.


----------



## W1zzard (Dec 12, 2013)

Maybe look at how developers of popular packages do it? I love NodeJS, really awesome what it can do and how well it scales


----------

