Search code examples
node.jsgruntjsrequire

Node's module.exports comes back as an empty object


I'm trying to build some utility modules for a grunt build process. Apparently I'm confused on how the module system works, but here is what I have (leaving out function logic since it's irrelevant):

var modifiers = {
    task: function(grunt){
       //logic...
    }
}

var modify = function(grunt){ 
    modifiers.task();
}

module.exports = {
    modify: modify
};

And then from a calling file:

var modifiers = require('./modifiers');

// later in file....
grunt.log.writeln(JSON.stringify(modifiers)); //outputs: {}

So the log call outputs an empty object. Calling modifiers.modify gives an error:

Warning: modifiers.modify is not a function

Am I completely missing how module.exports works? I am using it in other files to export functions but I really need the whole private-variable semantic here.

I've also tried setting module.exports to a self-calling function that returns an object, along with other stuff -- to no avail. How do I get it to just return the modifiers object? It needs to be extensible, thus me wanting to return an object.

Any help would be huge. Thanks.


Solution

  • JSON.stringify() does not serialize function properties so since your modifiers object only has a single property that is a function, JSON.stringify() shows an empty object.

    A test like:

    console.log(modifiers);
    

    or

    console.log(modifiers.modify);
    

    will show what you expect if your module is working properly.

    If calling modifiers.modify() creates an error, then you must have an error loading your ./modifiers module and your console should show some sort of error when loading it.