Question

I'm trying to understand the difference between the following two alternate representations of what I thought was the same functionality.

apiRegistry1.js

module.exports = function () {
    var apiRegistry = {};
    var files = fs.readdirSync('./apis');
    for (var index in files) {
        var fileName = files[index];
        var module = fileName.split('.')[0];
        apiRegistry[module] = require('../apis/' + module);
    }
    // console.log(apiRegistry) --> Prints {key: moduledef ..}
    return apiRegistry;
};

vs

apiregistry2.js

var apiRegistry = {};
var files = fs.readdirSync('./apis');
for (var index in files) {
    var fileName = files[index];
    var module = fileName.split('.')[0];
    apiRegistry[module] = require('../apis/' + module);
}

// console.log(apiRegistry) --> Prints {key: moduledef ..}
module.exports = apiRegistry;

server.js

var apiRegistry1 = require('./includes/apiregistry1')(); // returns {key: moduledef ..}
var apiRegistry2 = require('./includes/apiregistry2'); //returns {}

apiRegistry1 behaves as I would expect, but 2 doesn't. On some level it makes sense that 1 is a function and is evaluated when it's called, and that's why it works but I don't understand why printing the value within the module always works, but referencing outside of it doesn't. Is there something fundamental about how require works that I'm missing?

Was it helpful?

Solution

var module = fileName.split('.')[0];

is the culprit.

Because of how scoping works in JavaScript, that module variable isn't local to the for loop but instead the whole file. Thus, when you use it at the end:

module.exports = apiRegistry;

you are setting the exports property on your own module variable instead of the one node expects you to use. Changing to using another variable name solves your problem:

var apiRegistry = {};
var files = fs.readdirSync('./apis');
for (var index in files) {
    var fileName = files[index];
    var myModule = fileName.split('.')[0];
    apiRegistry[myModule] = require('../apis/' + myModule);
}

// console.log(apiRegistry) --> Prints {key: moduledef ..}
module.exports = apiRegistry;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top