Reputation: 2767
I have two modules:
InternalDefs.js:
const internalLevel = 0;
module.exports = {
internalLevel
};
ExternalDefs.js:
const { internalLevel } = require('./InternalDefs');
const exportedLevel = internalLevel;
module.exports = {
exportedLevel
};
The InternalDefswill contain definitions that should only be used in ExternalDefs.
The functionality if both files will be exported through ExternalDefs and everyone who wishes to use the functionality should only use the ExternalDefs.
This is an encapsulation of the internal operation. For example a database module.
ExternalDefs will have the functions that will be used. InternalDefs will serve the external functions only.
So, is there a way to allow only ExternalDefs to require the exports of InternalDefs in Node.js?
Upvotes: 1
Views: 1160
Reputation: 1689
It's probably a bad idea to try to restrict it like this. Ideally you should define them in one file and whatever is defined internally without being exported would be your internal data. Once exported, it is available for everyone.
But if you must, you can write this code in internalDefs.js to limit it to being required only by externalDefs.js. Add this early to internalDefs.js
if (!(module && module.parent && module.parent.filename && module.parent.filename.endsWith && module.parent.filename.endsWith("/ExternalDefs.js")))
throw new Error("InternalDefs is only allowed to be required by ExternalDefs");
Upvotes: 1
Reputation: 531
If what you're saying is that you want a third class to only have access to ExternalDefs.js
only, and not InternalDefs.js
by reference to internalDefs
defined in ExternalDefs.js
, then it won't.
Any outside class require
ing ExternalDefs.js
will only have access to internalDefs
defined in ExternalDefs.js
and will not have access to the properties inside InternalDefs.js
If that's not you're question, I suggest you elaborate
Upvotes: 0