Astephen2
Astephen2

Reputation: 851

Issues with exports

I'm currently trying to build an array of functions. I have a folder full of modules where each module has a function run and the following line

 exports.run = run;
 var run = function(db){
   // Run some code
 }

I then have a file I call in node which does the following:

require("fs").readdirSync("./channels").forEach(function(file) {
  var func = require("./channels/" + file);
  channels.push(func);
  console.log("Adding " + file);
  console.log(channels);
});

The function above successfully adds in each file with type undefined. I'm unable to run the functions because of this. How can I successfully build this array of functions?

Upvotes: 0

Views: 44

Answers (1)

bevacqua
bevacqua

Reputation: 48566

The reason your code doesn't work as you expect it to, is variable hoisting in JavaScript.

var run = function(db){
    // Run some code
}

exports.run = run;

If you don't want to push your exports line to the bottom of your function, then you'll have to declare run as a stand-alone function, rather than assigning it to a variable.

exports.run = run;

function run(db){
    // Run some code
}

Upvotes: 4

Related Questions