Reputation: 803
I have a problem in which i'm using a file to hold a list of modules and requiring this list in one call in my nodejs server. I want to use the modules in the list in a specific way.
modules.js -
Mods = {
mymodule: require('./mymodule.js')
}
exports.f = function() {
return Mods;
}
index.js -
f = require('./modules.js').f;
f().mymodule.echo("Hello World");
so instead of how i'm using f() now i want to put the name of the module i'm calling directly into the function so I can do things like this:
f = require('./modules.js').f;
f('mymodule').echo("Hello World");
I've tried a number of different experiments but can't get it to work, is it possible to do this in javascript?
Upvotes: 0
Views: 138
Reputation: 606
Edit: I was asked to explain my answer and I'm pleased to do so. The key to the solution is what is called the bracket notation. This term refers to the ability to access a property on an object in JavaScript using a variable. In the code below you can see how the property of the object Mods
is accessed using [name]
where name
is a variable containing the name of the property as a string.
Mods = {
mymodule: require('./mymodule.js');
}
exports.f = function(name) {
return Mods[name];
}
Upvotes: 1
Reputation: 826
I would say more ... ^^
var Mods = {
mymodule: require('./mymodule.js');
}
module.exports = function( name ) {
if( !name ) return Mods;
return Mods[name];
};
Upvotes: 1
Reputation: 140228
Well, if you do this:
var Mods = {
mymodule: require('./mymodule.js');
}
module.exports = function( name ) {
return Mods[name];
};
You can then do:
var f = require( "./modules.js"); //no .f required
f( "mymodule" ).echo( "Hello world");
Upvotes: 1