Skip to content Skip to sidebar Skip to footer

Node.js Module/export System: Is It Possible To Export A Module As A Function

I want to do something like this in Dispatch.js function handle(msg) { .... } exports = handle; and this in the calling index.js var dispatch = require('./Dispatch); dispatch(

Solution 1:

exports = handle

This creates a local variable called exports. This is different from overwriting module.exports.

module.exports = handle

This overwrites the exports variable that lives in module scope, this will then be read by require.

In the browser window["foo"] and foo are the same, however in node module["foo"] and foo behave subtly different.

The local variable scope context and module are not the same thing.

Solution 2:

Do:

function handle(msg) {
    ....
}
module.exports = handle;

and it works the way you want.

Solution 3:

The problem behind this issue (exports vs module.exports vs exports.something) is best described in this article:

http://www.alistapart.com/articles/getoutbindingsituations

The first version (exports = handle) is exactly the problem: the missing binding that is mandatory in javascript:

exports = handle means window.exports = handle (or whatever node.js has as the global object)

Solution 4:

Another way of seeing the problem is thinking about how node could load your module:

function loadModule(module, exports) {

inside here comes your module code

}

If your code overwrites the exports parameter (exports = handle), this change is not visible from the outside of this function. And for this overwriting one can use the module object.

The problem would not occur if exports would be a variable visible in the scope where the function body is.

Post a Comment for "Node.js Module/export System: Is It Possible To Export A Module As A Function"