0

I have the following code:

var tableRequiredList = [];

var requireListPath = [
    './slimShady.js',
    './chickaChicka.js'
];

var getRequires = function() {
  for (var i = 0; i < requireListPath.length; i++) {
    ((requireNamePath) => {
      try {
        console.log("INSIDE LOOP RESULT", i, require(requireNamePath)().getName()); // Outputs correct result for the index ("ChickaChicka")
        tableRequiredList.push({ "name": requireNamePath, "theReq": require(requireNamePath)() });
        // tableRequiredList.push({ "name": requireNamePath, "theReq": ((thePath) => { return require(thePath)(); })(requireNamePath) }); // This also doesn't seem to work.
      } catch(err) {
        console.log("Error importing: ", requireNamePath, "  Error reported: ", err);
      }
    })(requireListPath[i]);
  };
  console.log("NAME", tableRequiredList[0].name); // Outputs the correct result ("slimShady.js")
  console.log("FUNC NAME", tableRequiredList[0].theReq.getName()); // Always outputs the last item in requireListPath list ("ChickaChicka")
};

getRequires();

Example Module 1 - slimShady.js

((module) => {
  module.exports = {};

  var exampleModuleName1 = function() {

    this.getName = function() {
      return 'myNameIsSlimShady';
    };

    return this;
  };

  module.exports = exampleModuleName1;
})(module);

Example Module 2 - chickaChicka.js

((module) => {
  module.exports = {};

  var exampleModuleName2 = function() {

    this.getName = function() {
      return 'ChickaChicka';
    };

    return this;
  };

  module.exports = exampleModuleName2;
})(module);

Why does it output:

INSIDE LOOP RESULT 0 myNameIsSlimShady
INSIDE LOOP RESULT 1 ChickaChicka
NAME ./slimShady.js
FUNC NAME ChickaChicka

When it should be outputting the first index of the tableRequiredList array? This seems to only happen with require(). I have tried using map and forEach, along with the closure example above. All have the same results.

Slyke
  • 72
  • 1
  • 8

1 Answers1

0

Thanks to @liliscent, I figured it out.

Just needed to change modules to this:

((module) => {
  module.exports = {};

  var exampleModuleName2 = function() {
    var retr = {};

    retr.getName = function() {
      return 'ChickaChicka';
    };

    return retr;
  };

  module.exports = exampleModuleName2;
})(module);
Slyke
  • 72
  • 1
  • 8