LittleBobbyTables
LittleBobbyTables

Reputation: 4473

Nodejs: Run a function in an arbitrary module?

Let's say I have a directory full of javascript files:

.
+-- my_dir
    +-- apple.js
    +-- banana.js
+-- main.js

And each file in the subdirectory contains a function called setup().

How can I iterate through all the files and run that function?

This is as far as I've got:

var fruit = {}
var normalizedPath = require("path").join(__dirname, "fruit");

require("fs").readdirSync(normalizedPath).forEach(function(file) {
  filename = file.split(".")[0] //remove the file extension
  algorithms[filename] = require("./fruit/" + file); //load the file
  //run the setup function in it
  algorithms[filename].setup()
});

But this can't access the function, returning "undefined is not a function"

Upvotes: 0

Views: 138

Answers (1)

Patrick Gunderson
Patrick Gunderson

Reputation: 3281

You need to export setup() from each of your modules.

a-module.js

var obj = {};

obj.setup = function(){
    // doStuff
}

module.exports = obj

Upvotes: 1

Related Questions