Startec Startec - 21 days ago 6
Node.js Question

What is the effect of passing exports to an anonymous function

I was looking at the code for the node-etherdream library and in the main module I saw this:

(abbreviated):

(function(ns) {
/// a bunch of code

})(exports);


I have never seen
exports
being passed into an anonymous function like this, nor do I see
module.exports
anywhere in this code. Yet, this file is being
reuire
d like any other module.

Can someone explain this use of
exports
to me?

Answer

The exports is special object that you can set variables into. So in this example when the function executes it passes this object exports.

If you want to export some variable you can set it in ns variable(exports) in this case like that:

(function(ns) {
/// a bunch of code
    ns.func1 = function(){}

    ns.func2 = function(){}

    ns.age = 20
})(exports);

When you require the file from other file you will get access to this variables func1, func2 and age like that:

var o = require('file.js')
o.func1();
o.func2();
o.age // => 20