0

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?

1
  • 3
    Captain Zero, I suggest you work on your name, over. Commented Dec 3, 2012 at 13:54

3 Answers 3

1

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");
Sign up to request clarification or add additional context in comments.

Comments

1

I would say more ... ^^

var Mods = {
    mymodule: require('./mymodule.js');
}

module.exports = function( name ) {
  if( !name ) return Mods;
  return Mods[name];
};

Comments

1

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];
}

1 Comment

Please think about adding a comment to your code only answer.

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.