I would like to have a module for Node.js that is a directory with several files. I'd like some vars from one file to be accessible from other file, but not from the files external to the module. Is it possible?
So let's suppose the following file structure
` module/
| index.js
| extra.js
` additional.js
In index.js
:
var foo = 'some value';
...
// make additional and extra available for the external code
module.exports.additional = require('./additional.js');
module.exports.extra = require('./extra.js');
In extra.js
:
// some magic here
var bar = foo; // where foo is foo from index.js
In additional.js
:
// some magic here
var qux = foo; // here foo is foo from index.js as well
Additional and Extra are implementing some business logic (independent from each other) but need to share some module-internal service data which should not be exported.
The only solution that I see is to create one more file, service.js
and require
it from both additional.js
and extra.js
. Is it correct? Are there any other solutions?
Can you just pass the desired stuff in?
Yes, it is possible. You can load that other file into your module and hand it over a privileged function that offers access to specific variables from your module scope, or just hand it over the values themselves:
index.js:
extra.js:
additional.js:
Okay, you may be able to do this with the "global" namespace:
and then