Lee Quarella
Lee Quarella

Reputation: 4732

Jasmine-Node Require *

In my Jasmine-Node spec_helper I have require("../app/test") and it pulls in that test file just fine. But if I try require("../app/*"), I get Error: Cannot find module '../app/*'.

Is there a way to pull in all the files/sub-dirs of a directory like this?

Upvotes: 1

Views: 907

Answers (1)

Linus Thiel
Linus Thiel

Reputation: 39223

There are a few ways to accomplish what you want, the easiest probably being to create an index.js in your ./app directory. This index.js would in turn reference all the modules inside that directory, and export them:

exports.foo = require("./foo");
exports.bar = require("./bar");

If you want to do it dynamically, you will have to write some code:

var fs = require("fs");

fs.readdir("./app", function(err, files) {
    if(err) console.error(err);
    for(var i = 0, len = files.length; i < len; i++) {
        require("./app/" + files[i]);
    }
});

For more info on how node loads modules, here's the relevant docs and about folders as modules in particular.

Unfortunately, Jed's answer here is wrong.

Upvotes: 2

Related Questions