4

I am working on a CMS system for Node.js, I have a quick question for those Node.js Pro's

I am creating modules and requiring modules within those modules, but if I have already included this module in the parent module, can I access those required modules?

For Example:

main.js
    var fs = require('fs');
    var sc = require('second.js');


second.js
    var fs = require('fs'); // Is there any way to use the parent modules fs object?

It just seems I am including the same modules in some of my sub modules and rather not do that if possible.

Thanks!

2 Answers 2

12

In case you came here looking for a simple way to get the parent module from the current module, here's a way of doing that:

var parent = module.parent.exports;

The module object stores quite a bit of useful information, including a reference to the parent module that loaded it. You could also do it like so:

var parent = module.require( module.parent.id );
Sign up to request clarification or add additional context in comments.

1 Comment

It may be worth noting that module.parent refers to the parent who first loaded the module, not the parent in that particular instance.
6

It shouldn't matter, since Node caches modules when they're first included (i.e. the side-effects of requiring a module won't be executed a second time). You can force this cache to be cleared (and thus re-execute said side-effects) by tampering with require.cache.

2 Comments

I did read that, but just seems redundant. But if there is no disadvantages, then I will just keep re-including them.
I think that is the way to go with a modular system as each module has a clear "input" (requires and function parameters) and an "output" (exports).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.